If I have this for a child view controller:
autoCompleteViewController.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.act
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:
autoCompleteViewController.view
is not yet instantiated.isActive = true
at the same time. I've always gotten a build error.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
}
}
Good luck!
First you have disable the previous constraint and activate another
For example
let heightAnchor_one = autoCompleteViewController.view.heightAnchor.constraint(equalToConstant: x)
let heightAnchor_two = autoCompleteViewController.view.heightAnchor.constraint(equalToConstant: y)
heightAnchor_one.isActive = true
heightAnchor_two.isActive = false
then whichever constraint you need activate that and disable the other.
I've fixed it by implementing it like this:
autoCompleteViewControllerHeight = NSLayoutConstraint(
item: autoCompleteViewController.view,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .height,
multiplier: 1.0,
constant: 44.0)
guard let autoCompleteViewControllerHeight = autoCompleteViewControllerHeight else { return }
autoCompleteViewControllerHeight.isActive = true
and then where it should be changed I added:
let newHeight = calculateNewHeight()
heightConstraintAutoCompleteViewController.constant = newHeight
It works like a charm.
You can do something like this:
class ViewController: UIViewController {
var constantValue: CGFloat = 44
let childView: UIView = {
let view = UIView()
view.backgroundColor = .red
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(childView)
childView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
childView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0),
childView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0),
childView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0),
childView.heightAnchor.constraint(equalToConstant: constantValue)
])
}
@IBAction func changeHeight(_ sender: UIButton) {
constantValue = 100
UIView.animate(withDuration: 0.5, animations: {
if let constraint = (self.childView.constraints.filter{$0.firstAttribute == .height}.first) {
constraint.constant = self.constantValue
}
self.view.layoutIfNeeded()
})
}
}