Abhinav
Abhinav

Reputation: 3428

Update constraints of other elements when UITableView height change

I have a UITableView of which I am defining height as 200 in autolayout. Based on that I am laying out other elements below it like UITextField etc. After that in run time I am fetching data from server and populating in UITableView due to which i am updating UITableView's height based on its content size. Following code I am using for it

self.myTableView.frame = CGRectMake(0 , 0, self.myTableView.frame.width, self.myTableView.contentSize.height)

But due to this, all the elements placed below UITableView still appear at same location which they were while laying out in Autolayout. Means change in height of UITableView makes no difference to them. Following image depicts this problem. What could be possible solution for this?

enter image description here

Here you can see, text fields are getting overlapped on tableview at run time. I am using Swift 2 in Xcode 7.2

Upvotes: 3

Views: 10746

Answers (3)

Mobile Apps Expert
Mobile Apps Expert

Reputation: 1048

You have to create an outlet connection for your table view height constraint:

@IBOutlet var heightConstraint: NSLayoutConstraint!

and when you want to change table view height, you can change the constraint value like this:

heightConstraint.constant = newHeightValue
self.view.layoutIfNeeded()

Upvotes: 0

Hitendra Solanki
Hitendra Solanki

Reputation: 4941

If you have all required constraints to your table view and other view.

Don't change the frame of TableView to change height of it. Instead create IBOutlet of height constraint of your tablview.

e.g. say IBOutlet name is constraintTableViewHeight, then you can the the hight easily.

constraintTableViewHeight.constant = yourNewHeightValue
//update all constraint of your view and its inner view
self.view.layoutIfNeeded();

Refer Image to create IBOutlet for your height Constraint.

enter image description here

Upvotes: 7

Jaydeep Patel
Jaydeep Patel

Reputation: 1739

Take IBOutlet of NSLayoutConstraint for tableView Height and set its value not set tableview frame it's not working if you are already given constraints for tableview so change tableview hight constant

like if you take tblHeight for tableView height then set tblHeight.constant = self.myTableView.contentSize.height

Upvotes: 1

Related Questions