Adopting Component-Based Programming | Swift

Abu Bäkr
3 min readMar 22, 2021

Say you are building an iOS application, and there is a UIComponent that is being used in almost every screen. Will you act as a noob programmer, and write code for that component in every screen? Definitely not! Being a good programmer, we want to minimise our code, with maximising the output.

Component based programming can play a vital role in achieving this goal. You observe a UI Element that is being used repeatedly, you write code for that element only ONCE, in a way that you can reuse the code easily and efficiently.

Let’s say we have a button at the bottom of our ViewController, which is being used in multiple screens. We’ll make that button a component, and will reuse it along with different customisations.

We’ll start off by writing a function name addButtonToBottom which will be in an extension of UIView. Inside that function, make a UIButton, and apply constraints to it.

Creating Button

Creating a UIButton

Adding Constraints to Button

Inside the same function, add constraints to UIButton.

Constraints to UIButton

Here self refers to the view, in which the button will be added. We are centring the button horizontally relative to the view in which we want to add the button, and we are giving -20 px bottom margin. That’s it. We are almost done with the code. All we have done is that we wrote a function in extension of UIView, and inside that function, we have created a UIButton and given it constraints. Now to use it in any class, we’ll do it like so :

Final Result

You can also customise the button by adding more parameters to the function.


Component-based programming can help in cleaner and efficient coding. It prevents the programmer from repeating a chunk of code over and over, and also eliminate the effort of correcting any line of code if it is written in many places.

Happy Coding!