【问题标题】:UITableView not shown inside UIStackViewUITableView 未显示在 UIStackView 中
【发布时间】:2016-09-14 01:18:03
【问题描述】:

我有一个UIStackView,它可以根据用户选择显示标签、图像、表格视图或任何内容。这是我当前的动态视图层次结构:

  • UIStackView_Parent
    • UILabel - 一些文本,固定视图
    • UIStackView_Child - 这是可以显示多个内容或什么都不显示的容器
    • UIView - 另一个固定视图

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

任何帮助将不胜感激,谢谢!

【问题讨论】:

    标签: ios swift uistackview


    【解决方案1】:

    不显式设置框架高度和宽度的另一种方法是将表格视图嵌入空视图中,将表格视图固定在顶部、底部、左侧和右侧,并设置“大于或等于”约束表视图的高度。

    【讨论】:

    • “大于或等于”约束?这是否将“空视图”的高度限制为 >= 表格的高度?
    • @kliron 你能详细说明一下,也许有截图或例子。我直接在视图和父单元格上设置了大于约束,但无法使其工作。
    【解决方案2】:

    那是因为 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 应该会自动调整。

    【讨论】:

    • “你必须做两件事之一”另一件事是什么?
    • 其他可能是表格视图的高度限制。例如,tableView.heightAnchor.constraint(equalToConstant: 42).isActive = true。设置堆栈视图高度也可以。
    • 为什么estimatedHeight是行数?它应该乘以行高。
    【解决方案3】:

    你也可以通过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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-28
      • 2020-01-23
      • 1970-01-01
      • 2021-04-11
      相关资源
      最近更新 更多