Антон Тотошкин Антон Тотошкин - 5 months ago 13
Swift Question

tableView change height in swift

I have dynamic cell count in my tableView, how can I change tableView height?

I try, but it's not work:

self.tableView.frame.size.height = CGFloat(height)

Answer

If you are not using the autolayouts then below code would work:

    func adjustTableViewHeight() {
        var height = tableView.contentSize.height
        let maxHeight = (tableView.superview?.frame.size.height)! - self.tableView.frame.origin.y

       if height > maxHeight {
           height = maxHeight
       }

        UIView.animateWithDuration(0.5) { 
            var frame = self.tableView.frame
            frame.size.height = height
            self.tableView.frame = frame
        }
    }

If you are using autolayouts then use this:

    func adjustTableViewHeight() {
        var height = tableView.contentSize.height
        let maxHeight = (tableView.superview?.frame.size.height)! - self.tableView.frame.origin.y

       if height > maxHeight {
           height = maxHeight
       }

        UIView.animateWithDuration(0.5) { 
           //Assuming 'tableViewHeightConstraint` is an IBOutlet from your storyboard/XIB
            self.tableViewHeightConstraint.constant = height
            self.tableView.setNeedsUpdateConstraints()
        }
    }
Comments