ios using constraints to hide a view

124 Views Asked by At

Why is it that if I have a simple viewcontroller with a button, a "control view" and a tableview below it, I can't get the logic to work that will expand the tableview to cover the "view" when the button is pressed and then restore if pressed again. The table will overlay the "control view" but when pressed a second time, does not "restore" the table below the "control view"

@IBAction func buttonPressed(_ sender: Any) {

        if bControlHide == false {
            myTableView.translatesAutoresizingMaskIntoConstraints = false
            myControlView.translatesAutoresizingMaskIntoConstraints = false
            myTableView.topAnchor.constraint(
                equalTo: myControlView.topAnchor).isActive = true
            bControlHide = true
        }
        else {
            bControlHide = false
            myTableView.translatesAutoresizingMaskIntoConstraints = false
            myControlView.translatesAutoresizingMaskIntoConstraints = false
            myTableView.topAnchor.constraint(
                equalTo: myControlView.bottomAnchor).isActive = true
        }
    }
3

There are 3 best solutions below

0
On BEST ANSWER

If your controlView has fixed height,

1) Make an outlet for the controlView height from storyboard to ViewController and set it to 0 when you need to hide it. Set another value when you unhide.

Do not forget to set 0 controlView bottom space to tableView, otherwise tableView will not cover your controlView.

1
On

You should set the height of tableview and also tableview should be constrained to top and bottom vertical spacing(if you want to support different devices).

Initial setup would be:

  • height constant is greater than 0
  • height priority is 1000
  • bottom constraint is 0
  • bottom priority is 750

When you tap to button you just need to change priorities:

  • height priority is 750
  • bottom priority is 1000
0
On

Please pay attention to the following codes:

myTableView.topAnchor.constraint(equalTo:myControlView.topAnchor).isActive = true
myTableView.topAnchor.constraint(equalTo: myControlView.bottomAnchor).isActive = true

Every time you call myTableView.topAnchor.constraint will add a new constraint, this is not what you want.

So please create and save the two constraints to member variables, and then activate or deactivate it according to your needs.

BTW, you don't have to set translatesAutoresizingMaskIntoConstraints every time when you click button, set it once in xib or in viewDidLoad