【问题标题】:Swift height of content of table view表格视图内容的快速高度
【发布时间】:2017-04-24 18:10:49
【问题描述】:

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

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

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

【问题讨论】:

标签: swift uitableview height constraints


【解决方案1】:

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

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
    }
}

【讨论】:

  • 我应该在哪里调用它以确保表已加载?我在视图中尝试了加载,它说高度为 0。
  • 如果可以的话不要忘记 +1 :)
【解决方案2】:

使用tableview的内容大小属性来获取其中内容的高度:

tableView.layoutIfNeeded
let tblSize = tbl_Data.contentSize
print(tbl_Data.contentSize.height)

【讨论】:

    【解决方案3】:
    1. 设置tableview高度出口。
    2. 现在使用获取 tableview 内容大小并设置为 willDisplayCell 作为 tableview 的高度。
    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
      }
      

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 2021-06-03
      • 1970-01-01
      • 1970-01-01
      • 2016-10-20
      相关资源
      最近更新 更多