'Get Height of Table Contents in Swift

I'm trying to get the height of all of a table's contents so I can update the container it is in. This will allow the container and other views in the scroll view to scroll together.



Solution 1:[1]

Swift:

var tableViewHeight: CGFloat {
    tableView.layoutIfNeeded()

    return tableView.contentSize.height
}

Objective-C

- (CGFloat)tableViewHeight {
    [tableView layoutIfNeeded];

    return [tableView contentSize].height;
}

Solution 2:[2]

Swift 3

override func viewDidLoad() {
    super.viewDidLoad()

    myTbleView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)
}

override func viewWillDisappear(_ animated: Bool) {
    myTbleView.removeObserver(self, forKeyPath: "contentSize")
    super.viewWillDisappear(true)
}

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
           tableViewHeightConstraint.constant = newsize.height
        }
    }
}

Hope this will help you.

Solution 3:[3]

var obs: NSKeyValueObservation?
obs = tableView.observe(\.contentSize, options: .new) { (_, change) in
    guard let height = change.newValue?.height else { return }
    self.constantHeight.constant = height
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 ram880
Solution 3 Ahmed Safadi