Building UIControl Extensions

While working on my new Udemy course, I had the requirement of displaying a UIButton control on top of a MapView control. I decided to add the control dynamically and came up with the following implementation:

The above code works and it does add the button to the view, but it is too much code to be injected into the view controller. There has to be a way to write code in more reusable way.

Turns out you can create UIControl extensions which can be responsible for configuring the control. Take a look at the UIButton control extension implemented below:

Now, if I want to create a particular control I would simply write the following line:

We can take this one step further and allow our extensions to add constraints. For this we introduced a new extension on UIView as shown below:

The UIView extensions deals will all the code necessary to add various constraints to the UIView controls. Now, we can use our UIButton along with the UIView extension as shown below:

Much nicer and cleaner!

I am not too happy about the casting to UIButton call in the end. If you find a way to remove that call while keeping the code clean then please add it in the comments below.

If you have liked this post and want to support me then please take a look at the courses I offer on Udemy.

Thanks and happy coding!

iOS Developer, speaker and educator. Top Udemy and LinkedIn instructor. Lead instructor at DigitalCrafts.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store