Simplifying Autolayout Code with Swift

This evening I found myself staring at a block of Autolayout code, thinking to myself: “There must be a better way”. Of course, the ideal is to do all your Autolayout in Interface Builder, but every now and then there are times when you just have to use some code. My code looked something like this:

I understand Apple’s preference for clarity over terseness but, in this case, I think clarity is suffering at the hands of verbosity. With Swift’s default arguments and ability to suppress parameter labeling I think we can do better. My first attempt to simplify the code was to add the following two functions to my project.

With these in place the code becomes:

This is already a great improvement (at least to my eyes), but we can go a little further. There is a lot of repetition of the toolbarView variable in the above code. We can cut this out by extending UIView.

Finally the code becomes:

I think this makes it much clear what’s going on.

About idz

A professional software engineer dabbling in iOS app development.
This entry was posted in Programming, Swift. Bookmark the permalink.

2 Responses to Simplifying Autolayout Code with Swift

  1. Pingback: Issue #7 – October 10, 2014 | iOS Dev Newbie

  2. Pingback: [整理]swift的视图的布局的约束 | 在路上

Leave a Reply