![](/img/trans.png)
[英]Objective-c: Dynamic size of UIStackView, depending of it's content
[英]How to size a UIStackView depending on its content?
在框架根据其内容调整大小的意义上,我希望具有与<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
之间的约束。 例如,如果UIStackView
是第一项,而UITableViewCell
是它的超级视图,那么这就是界面生成器中约束的样子:
如果您喜欢在代码中设置约束,那也应该可以。
例如,假设stackView
和cellView
是名称,那么上述约束的 Swift 代码将如下所示:
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: cellView.topAnchor, constant: 0).isActive = true
stackView.bottomAnchor.constraint(equalTo: cellView.bottomAnchor, constant: 0).isActive = true
stackView.leadingAnchor.constraint(equalTo: cellView.leadingAnchor, constant: 0).isActive = true
stackView.trailingAnchor.constraint(equalTo: cellView.trailingAnchor, constant: 0).isActive = true
为了证明这将起作用,我将它用于cellForRowAt
函数。 基本上,它在UIStackView
中放置了一些UILabel
并且标签计数取决于行号。
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
}
这是最终结果:
我构建了这个示例,希望对您有所帮助,我创建了一个 tableView,它使用一个包含 stackView 的单元格,并且在 stackView 中加载的视图是从一个 nib 文件中获取的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.