How do I update a constraint from the Storyboard without an IBOutlet or Identifier?

339 Views Asked by At

I have a lot of views that are created in the storyboard, but I want them to be able to update their constraints dynamically without having to use an IBOutlet each time.

I started by making a custom class for the superview of the view I want to update, and change its subview's bottom constraint like this:

    myView.constraints.filter{ $0.firstAnchor is NSLayoutAttribute.bottom }.constant -= 200

'NSLayoutAttribute.bottom' doesn't seem to be the correct way to check the type of the Anchor.

How do I check the type of the constraints I want to change?

Am I correct in updating the constraints in the superview of the view I want to change, not the view itself?

2

There are 2 best solutions below

3
On

NSLayoutConstraint from iOS7 have a property called identifier, from code or from IB you can set this property.
After that to get the constraint you are looking for is just a matter of searching it in a particular view.
Consider this UIView extension:

func constraint(withIdentifier:String) -> NSLayoutConstraint? {
        return constraints.filter{ $0.identifier == withIdentifier }.first
    }
0
On

As per dahlia_boy's suggestion, I used UIView.animate to achieve this functionality, however it doesn't seem to be permanent:

translatesAutoresizingMaskIntoConstraints = true
UIView.animate(withDuration: 1, animations: {
    self.frame.size.height -= 200
})