Now that all the constraints are set and our views align nicely, we can now go into the coding section where we’re going to focus on how we manipulate the constraints with code. Also I’m going to show you how you could also create constraints using code although this is not something that I recommend when starting out, since the constraints get much harder to maintain and debug. However if your working with other people on the same project it soon becomes necessary to only work with views inside of code because for example if you’re dealing with git you can resolve merge conflict much much easier. In the beginning however I recommend you use the Interface Builder to practice Auto-Layout because the visual components make understanding it much easier and this knowledge will serve you well later when you start to only use code.

Before we can deal with the constraints in code however, we need to have constraints to work with. Firstly I’m going to show you how you can connect your existing constraints to the code files via an @IBOutlet and then later we’ll dive into the creating constraints with code without making use of the Interface Builder.

Let’s connect an existing constraint to code for now. We’re going to take the center X constraint from our logo and connect it to code so we can set it during runtime. For this to see it take action we’re going to implement a button at the bottom of the page that will set the constraint to a new value.

We’re first going to place the button just below the logo, assign constraints to it, so we can see if all the time on all devices and connect the action from the button to our code.

To be able to do that I’m just going to switch the view from the standard editor to the assistant editor and select the file that should be displayed in the assistant editor.

Now let’s do the same thing with the constraint. Find the Constraint you want to work with in the outline view of your scene and select it. Now control-drag it into the assistant editor and let go. You can give the variable a name and viola, the constraint is connected to code. It works just like with any other object in your view.

The Only thing that is left to do now is to increase the constant of the connected constraint when the button is pushed. Finally, you can run the app.

Ask Anything!

Do you have any questions? Ask them! I'll answer via Email as soon as I read it.

Not readable? Change text. captcha txt