UITableView 未在 UIStackView 中显示

UITableView not shown inside UIStackView

我有一个 UIStackView,它可以根据用户选择显示标签、图像、table 视图或什么都不显示。这是我当前的动态视图层次结构:

当我用标签或图像调用 UIStackView_Child.addArrangedSubview(...) 时,它工作得很好,但 addArrangedSubview(tableView) 不显示 table。我有 tableView.scrollEnabled = false 并根据单元格数量将框架设置为固定高度,并定义了 table 的 cellHeight

非常感谢任何帮助,谢谢!

那是因为 stackview 试图尽可能地压缩内容。当您最初添加 table 视图时,我假设它没有内容,因此 stackview 将宽度压缩为 0,因为它没有任何内容可显示。您必须执行以下两项操作之一:

在 table 填充数据后,您必须设置 table 视图的框架。我通过计算每个单元格的大小来做到这一点。我知道宽度将与包含 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 应该会自动调整。

另一种无需明确设置框架高度和宽度的方法是将 table 视图嵌入空视图中,将 table 视图固定到顶部、底部、左侧和右侧并将 "greater than or equal to" 约束设置为 table 视图的高度。

您还可以使用 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 = [=10=].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
    }
}