Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 802
Austin E Avatar asked Jun 26 '16 04:06

Austin E


3 Answers

Swift:

var tableViewHeight: CGFloat {
    tableView.layoutIfNeeded()

    return tableView.contentSize.height
}

Objective-C

- (CGFloat)tableViewHeight {
    [tableView layoutIfNeeded];

    return [tableView contentSize].height;
}
like image 176
CodeBender Avatar answered Nov 13 '22 07:11

CodeBender


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.

like image 41
ram880 Avatar answered Nov 13 '22 06:11

ram880


var obs: NSKeyValueObservation?
obs = tableView.observe(\.contentSize, options: .new) { (_, change) in
    guard let height = change.newValue?.height else { return }
    self.constantHeight.constant = height
}
like image 1
Ahmed Safadi Avatar answered Nov 13 '22 05:11

Ahmed Safadi