iosxcodenslayoutconstraintnslayoutanchor

ios using constraints to hide a view


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
        }
    }

Solution

  • 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.