【问题标题】:Setting the height of the UITableView when the height of the cells is dynamic当单元格高度为动态时设置 UITableView 的高度
【发布时间】:2017-12-14 05:35:36
【问题描述】:

我正在 swift 3 中为 iOS 开发一个应用程序,其中有一个视图控制器具有其他视图(UIImageView、UICollectionView),并且内容可以通过UIScrollView 滚动。 我想在中间某处添加UITableView。 UITableView 将具有动态高度的单元格。一切正常,除了我无法设置UITableView 的高度来包装其内容,以便UITableView 的所有单元格在不滚动表格的情况下可见。我想关闭UITableView 和表格视图的滚动以设置其高度以使所有单元格可见而无需滚动。

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

【问题讨论】:

    标签: ios uitableview swift3


    【解决方案1】:

    你可以试试这个

    // 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")
     }
    

    【讨论】:

    • 谢谢 Vikky。你救了我的命。 :) 工作完美。
    【解决方案2】:

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

    【讨论】:

    • tableView.contentSize.height 总是不提供正确的高度。所以对于工作解决方案,请参阅我的答案
    【解决方案3】:

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

    1. 做一个延迟动作:

      DispatchQueue.main.asyncAfter(deadline:DispatchTime.now() + 0.1) {
      // 获取 contentHeight 并设置 tableView`s frame
      }

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多