当单元格的高度是动态的时设置 UITableView 的高度

Setting the height of the UITableView when the height of the cells is dynamic

我正在 swift 3 中为 iOS 开发一个应用程序,其中有一个具有其他视图(UIImageViewUICollectionView)的视图控制器和内容可按 UIScrollView 滚动。 我想在中间某处添加一个 UITableViewUITableView 将具有动态高度的单元格。一切正常,除了我无法设置 UITableView 的高度来包装其内容,以便 UITableView 的所有单元格都可见而无需滚动 table。我想关闭 UITableView 和 table 视图的滚动以设置其高度,使所有单元格无需滚动即可可见。

我根本无法将单元格的高度乘以行数,因为每个单元格的高度也是动态的。

您无需手动计算高度,只需使用 tableView.contentSize.height

你可以试试这个

// add observer to your tableView to get its proper height when its 
//data is loaded. you can do this in view did load
 self.YourTableView.addObserver(self, forKeyPath: "contentSize",options: .new, context: nil)

// override this metod to observe for tableView height change
 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?){
if(keyPath == "contentSize"){

    if let newvalue = change?[.newKey]
    {
        let newsize  = newvalue as! CGSize
        // make height constraint for your table view and set to new size.
        // and here you can check if newSize.height is more than required tha you can set it to default
        if(newsize.height < defaultHeight)
        self.tableViewHeightConstraint.constant = newsize.height

    }else{
        self.tableViewHeightConstraint.constant = defaultHeight

    }
}
}

如果您遇到任何问题,请告诉我

记得移除观察者,否则应用会崩溃

deinit {
 self.YourTableView.removeObserver(self, forKeyPath: "contentSize")
 }

如果您的控制器有很多嵌套滚动视图,tableView.contentSize.height 无法提供实际的 contentHeight。所以如果你想获取contentHeight(设置tableview的高度),有两种方法:

  1. 做一个延迟动作:

    DispatchQueue.main.asyncAfter(deadline:DispatchTime.now() + 0.1) {
    // get contentHeight and set tableView`s frame
    }

  2. 在 scrollView 委托中获取正确的高度:

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let contentHeight = scrollView.contentSize.height
    }