How can I change height of UIView that already has height anchor?

Viewed 10344

If I have this for a child view controller:

autoCompleteViewController.view.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            autoCompleteViewController.view.topAnchor.constraint(equalTo: view.topAnchor, constant: 0),
            autoCompleteViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0),
            autoCompleteViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0),
            autoCompleteViewController.view.bottomAnchor.constraint(equalTo: googleMapViewController.view.topAnchor, constant: 0),
            autoCompleteViewController.view.heightAnchor.constraint(equalToConstant: 44.0)
        ])

how can I change its height and update heightAnchor? I've tried this:

autoCompleteViewController
            .view
            .heightAnchor
            .constraint(equalToConstant: initialHeightAutoCompleteViewController + CGFloat(numberOfSuggestions * 45))
            .isActive = true

but with no luck. I also tried to add layoutIfNeeded() and some other similar methods but it didn't work. How can I update view height with anchors?

5 Answers

If you don't want to keep a reference to the height anchor, here is an alternative:

myVC.view.constraints.forEach { (constraint) in
     if constraint.firstAttribute == .height
     {
         constraint.constant = newHeight
     }
 }
Related