0

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?

caziz
  • 23
  • 1
  • 7
  • Why you need to update your constraints? Is there any special requirement? – dahiya_boy Dec 22 '17 at 05:22
  • The updated constraint would dynamically move the view out of the way of the keyboard; I wanted this as a custom class so I wouldn’t have to rewrite the same functionality for every view that otherwise would not need a custom implementation – caziz Dec 22 '17 at 05:32
  • Instead of updating constraint, set view frame and use `uiview.animation` for animation. [Refer here](https://www.raywenderlich.com/173544/ios-animation-tutorial-getting-started-3) – dahiya_boy Dec 22 '17 at 05:42

2 Answers2

0

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
    }
Andrea
  • 26,120
  • 10
  • 85
  • 131
  • Right, but I'd like to avoid having to create identifiers for all my views that I want this functionality. Is there a way to search by constraint type? – caziz Dec 22 '17 at 06:14
  • Yes, check this answer https://stackoverflow.com/questions/26833641/ios-find-top-constraint-for-a-view – Andrea Dec 22 '17 at 07:46
  • Also this project from Erica Sadun on GitHub https://github.com/erica/Auto-Layout-Demystified/tree/master/2ndEdition/Constraints%20Pack/Constraint%20Matching – Andrea Dec 22 '17 at 07:48
0

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
})
caziz
  • 23
  • 1
  • 7