swift4xcode-storyboardios-ui-automation

Is there an easy way to convert the constraints that are already defined in storyboard into Swift code?


I have designed a ViewController in my Storyboard and I have adjusted all of its constraints respectively.

Now, I would like to animate most of these constraints.

So :

  1. I should define them again using Swift codes
  2. and write some codes to do the animations.

But it is very annoying to define the constraints again in Swift code while I already have them in Storyboard.

So, I was hoping someone could introduce me an easy way to achieve this automatically.


Solution

  • No, there are no built-in ways to render the IB constraints into Swift code. You could iterate through them and grab all their properties and do something like that, but that will get messy. There are too many different ways to create constraints programmatically, and even if some automated tool existed, I bet the code wouldn’t be very elegant. (As a general rule, tools that generate code programmatically don’t result in very good code.)

    I wonder about the whole concept. We often animate constraints generated by IB without going through all of this. The typical approach is to give these IB constraints @IBOutlet references and then you can programmatically change their constant values and then put the call to layoutIfNeeded in the animation closure. Or, if you must, you can deactivate them (again, using the outlets) and then do whatever animation you want and, if appropriate, re-activate those constraints later, if needed.

    But we can’t advise on to how to best achieve your animation in an IB view with constraints without more details about the nature of the animation.

    But this is an example of how you can animate change the position of a view that has constraints defined in IB: https://stackoverflow.com/a/28329399/1271826