Search code examples
iosswiftnslayoutconstraint

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


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?


Solution

  • Additionally to @Mukesh answer is simply updating the constraint:

    var heightAnchor:NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        heightAnchor = autoCompleteViewController.view.heightAnchor.constraint(equalToConstant:44.0)
        heightAnchor.isActive = true
    }
    
    func changeMyHeight(numberOfSuggestions: Int) {
        heightAnchor.constant = 44.0 + CGFloat(numberOfSuggestions * 45)
    }
    

    Notes:

    • You cannot fully declare this variable at the class level, as autoCompleteViewController.view is not yet instantiated.
    • You cannot set up the constraint and set isActive = true at the same time. I've always gotten a build error.