[英]UITableView not shown inside UIStackView
我有一个UIStackView
,它可以根据用户的选择显示标签、图像、表格视图或什么都不显示。 这是我当前的动态视图层次结构:
当我用标签或图像调用UIStackView_Child.addArrangedSubview(...)
,它运行良好,但addArrangedSubview(tableView)
不显示表格。 我有tableView.scrollEnabled = false
并根据单元格数量将框架设置为固定高度并定义表格的cellHeight
。
任何帮助将不胜感激,谢谢!
在没有明确设置框架高度和宽度的情况下执行此操作的另一种方法是将表视图嵌入到空视图中,将表视图固定到顶部,底部,左侧和右侧,并将“大于或等于”约束设置为表格视图的高度。
那是因为stackview试图尽可能地压缩内容。 当你初步添加一个tableview时,我假设它没有内容,所以stackview将宽度压缩为0,因为它没有任何显示。 你必须做两件事之一:
在表填充数据后,您必须设置tableView的框架。 我通过计算每个细胞的大小来做到这一点。 我知道宽度将与包含stackview的视图一样大。 所以它最终变成了类似的东西
let estimatedHeight = tableView.numberOfRows(inSection: 0) //You may need to modify as necessary
let width = parentView.frame.size.width
tableView.frame = CGRect(x: 0, y: 0, width: width, height: estimatedHeight)
设置tableView的框架后,stackview应自动调整。
您还可以使用Combine 自动监控UITableView 的高度:
import Combine
var tableViewHeightConstraint: NSLayoutConstraint?
var cancellables: Set<AnyCancellable> = []
// Table View Content Size monitor
tableView.publisher(for: \.contentSize)
.receive(on: DispatchQueue.main)
.sink { self.tableViewHeightConstraint?.constant = $0.height }
.store(in: &cancellables)
或者,如果您没有可用的组合,您可以添加一个观察者:
tableView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if(keyPath == "contentSize") {
// Here you could get from change or simple get it directly from the table view
tableViewHeightConstraint?.constant = tableView.contentSize.height
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.