我有一個UITableView
,UITableViewCell
有一個動態的UILabel
這將根據我從數據庫中獲得的數據添加。UITableViewCell高度動態子視圖swift
我使用類似
let testing = ["A", "B", "C", "D"] // This array is dynamic data
self.dictionaryTableView.estimatedRowHeight = 44
self.dictionaryTableView.rowHeight = UITableViewAutomaticDimension
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "vocabCell", for: indexPath)
var y = 0
for var i in 0..<self.testing.count {
let lbl = UILabel(frame: CGRect(x: 0, y: y, width: 50, height: 25))
lbl.text = self.testing[i]
lbl.numberOfLines = 0
cell.addSubview(lbl)
y += 20
}
return cell
}
但UITableViewCell
高度不會自動伸展來顯示所有內容的細胞。請幫助 下面是結果
編輯我加約束在UITableView中的cellForRowAtIndexPath中的UILabel,約束正在努力(我知道,當我花費了單元格高度),但細胞高度不全自動STRETCH時出
var bottomAnchor: NSLayoutYAxisAnchor = NSLayoutYAxisAnchor()
for var i in 0..<self.testing.count {
let lbl = UILabel()
lbl.text = self.testing[i]
lbl.numberOfLines = 0
lbl.translatesAutoresizingMaskIntoConstraints = false
cell.addSubview(lbl)
lbl.leftAnchor.constraint(equalTo: cell.leftAnchor, constant: 16).isActive = true
lbl.widthAnchor.constraint(equalTo: cell.widthAnchor).isActive = true
lbl.heightAnchor.constraint(equalToConstant: 25).isActive = true
if i == 0 {
lbl.topAnchor.constraint(equalTo: cell.topAnchor).isActive = true
} else {
lbl.topAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
bottomAnchor = lbl.bottomAnchor
}
return cell
非常感謝
爲什麼要添加多個標籤? 我的意思是你可以插入下一行字符 – SPatel
@ user3783161循環裏面cellForRowAt是不是一個好主意,你可以添加標籤,故事板的意見。你有沒有使用你的疑問? –
https://stackoverflow.com/a/30300870/8779236看這回答 –