How can you alter constraints that are set in the Storyboard?
I am trying to mimic the Twitter iOS profile page where the header shrinks as you scroll down.
I have a UIScrollView that takes up the entire view. I then have a UITableView within the UIScrollView. Within the storyboard I must set a fixed height for the UITableView. So is has the constraint of Equals Height = 350.
I then try to change the height of it programmatically:
tableView.frame = CGRectMake(0, 0, scrollView.frame.width, scrollView.frame.height - 30)
When I do this it doesn't affect the size of the UITableView at all. I'm assuming this is because of the storyboard constraints.
Am I missing something or do I need to do this programmatically to start with?
Open the Align menu with the yellow button selected and check Horizontally in Container, then click Add 1 Constraint. Now, select both buttons at the same time using the Shift key and, in the Align menu, check Leading Edges. Again, actually install the constraint by clicking Add 1 Constraint.
Auto Layout defines margins for each view. These margins describe the preferred spacing between the edge of the view and its subviews. You can access the view's margins using either the layoutMargins or layoutMarginsGuide property.
Auto Layout constraints allow us to create views that dynamically adjust to different size classes and positions. The constraints will make sure that your views adjust to any size changes without having to manually update frames or positions.
Don't fight against the constraint set in the Storyboard. Instead, you can create an @IBOutlet
to the height constraint by finding it in the Document Outline view and control-dragging from the constraint to your code. Give it a name like tableHeightContraint
.
@IBOutlet weak var tableHeightConstraint: NSLayoutConstraint!
Then, when you want to change the height of the UITableView
, modify the constant
property of the constraint:
tableHeightConstraint.constant = scrollView.frame.height - 30
As @BlackRider noted in the comments, sometimes it is necessary to trigger a layout after constraints have been changed.
Calling:
view.layoutIfNeeded()
will tell Auto Layout to do the apply the constraint if needed. This is especially true if you are animating the change. In that case, the layoutIfNeeded()
call is made inside of the animation block.
UIView.animateWithDuration(2) {
self.view.layoutIfNeeded()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With