Swift table 视图内容的高度

Swift height of content of table view

除了将所有部分的所有单元格的高度相加之外,还有没有办法找出 table 视图内容的高度?

我有 3 个部分,每个部分都有不同高度的单元格和可变数量的单元格。 所以我希望有一个系统方法来获取 table 视图内容的高度。

编辑:在其他类似问题的答案中没有任何地方说明在哪里调用 tableView.contentSize

您可以通过以下方式检索内容大小:

Swift / ObjC:

let contentSize : CGSize = self.tableView.contentSize
let width = self.tableView.contentSize.width
let height = self.tableView.contentSize.height

您可以使用它来了解您的 UITableView 是否已加载 (Swift 2.2):

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    if indexPath.row == (tableView.indexPathsForVisibleRows!.last! as! NSIndexPath).row {
        // End of loading
        let contentSize : CGSize = self.tableView.contentSize
        let width = self.tableView.contentSize.width
        let height = self.tableView.contentSize.height
    }
}

使用tableview的content size 属性获取其中内容的高度:

tableView.layoutIfNeeded
let tblSize = tbl_Data.contentSize
print(tbl_Data.contentSize.height)
  1. 设置 tableview 高度出口。
  2. 现在使用获取tableview内容大小并设置成 willDisplayCell as tableview height.
  3. 不要忘记如果标签数据超过1行然后设置标签行 是 0.

    覆盖 func viewDidLoad() { super.viewDidLoad() //重新加载表格视图 tblData.reloadData() }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell =  tableView.dequeueReusableCellWithIdentifier("myTableViewCell", forIndexPath: indexPath) as! myTableViewCell
        return cell
    }
    
     func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
     //Content wise tableview height
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
         constTblDataHeight.constant = tblData.contentSize
    }