【发布时间】:2018-04-09 20:53:06
【问题描述】:
我有一个UITableView,UITableViewCell 有一个动态的UILabel,它将根据我从数据库中获得的数据添加。
我正在使用类似的东西
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 添加了约束,约束正在起作用(我在消耗单元格高度时就知道了),但单元格高度不会自动伸展
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
非常感谢
【问题讨论】:
-
为什么要添加多个标签?我的意思是你可以插入下一行字符
-
@user3783161 在 cellForRowAt 内循环不是一个好主意,您可以添加标签、情节提要中的视图。您是否在 Google 上搜索过您的疑问?
-
@user3783161 关注这个问题,因为你有类似的问题。 stackoverflow.com/questions/18600047/…
-
@SPatel : 我需要多个 uilabel 因为每个标签都有一些特殊的属性(例如:显示在右侧,点击它会执行一个动作),不能只在一个标签中完成。有些数据有这些属性,有些数据没有。
标签: ios swift uitableview