我希望有一个类似于<Table>
HTML标签的行为,在这种意义上,框架的大小根据其内容而定。
在我的上下文中,我使用UIStackView作为UITableViewCell的内容视图。由于单元格中的项目是各种信息,因此单元格的最终高度应该是可变的。
我的策略是以编程方式将单元格构建为具有.Vertical轴的UIStackView,如下面的代码片段所示:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let sv = UIStackView(frame: tableview.frame)
sv.axis = .Vertical
cell.addSubview(sv)
for i in information {
let l = UILabel()
l.text = i
sv.addSubViewAndArrange(l)
}
return cell
}
不幸的是,单元格大小不适应内容,因此我必须自己设置单元格高度,如下所示:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return cellHeight // a constant
}
我怎么能解决这个问题?
UIStackView
旨在根据内容增加其大小。为了使其起作用,您需要在UIStackView
和UITableViewCell
之间设置约束。例如,这是约束在界面构建器中的样子:
如果你喜欢在代码中设置约束,那也应该有效。
为了证明这将起作用,我有cellForRowAt
函数。基本上,它在UILabel
中放置了一些UIStackView
,标签数量取决于行号。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableviewCell", for: indexPath) as! TableviewCell
for i in 1...indexPath.row + 1 {
let label = UILabel()
label.text = "Row \(indexPath.row), Label \(i)"
cell.stackView.addArrangedSubview(label)
}
return cell
}
这是最终结果: