Search code examples
swiftautolayout

Runtime constraint change


I have a UIViewController which contain is UITableView and UIView. UITableView is above of UIView. When UIView is hidden, UITableView should stick to the bottom of UIViewController. How do I do that automatically?

When UIView is not hidden.

When UIView is hidden.

When UIView is hidden, UITableView should stick to the bottom of UIViewController.


Solution

  • Follow these steps to set auto layout constraints:

    1) To bottomView :

    • Apply leading, trailing, bottom and height constraints to bottomView with respect to parent view

    2) To UITableView :

    • Apply leading, trailing, top constraints to tableView with respect to parent view.

    • Apply bottom constraint to tableview with bottomView which is below tableview.

    3) Select the height constraint of bottomView from storyboard's constraint hierarchy, and take an outlet for it:

    enter image description here

    @IBOutlet weak var heightConstraint: NSLayoutConstraint!
    

    4) In the method, where you are hiding your bottomView, just change the value of it's height constraint to zero like:

    bottomView.isHidden = true
    
    heightConstraint.constant = 0
    view.updateConstraintsIfNeeded()
    

    Hope this helps you