Austin E
Austin E

Reputation: 843

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.

Upvotes: 20

Views: 33192

Answers (3)

Ahmed Safadi
Ahmed Safadi

Reputation: 4590

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

Upvotes: 5

CodeBender
CodeBender

Reputation: 36610

Swift:

var tableViewHeight: CGFloat {
    tableView.layoutIfNeeded()

    return tableView.contentSize.height
}

Objective-C

- (CGFloat)tableViewHeight {
    [tableView layoutIfNeeded];

    return [tableView contentSize].height;
}

Upvotes: 52

ram880
ram880

Reputation: 1318

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.

Upvotes: 33

Related Questions