Extend those Native Classes!

Overriding & extending native classes to reap more usability through retroactive modeling

Mohaiminul Islam
InfancyIT
6 min readMar 14, 2018

--

As I mentioned in my previous article about globally available functions, sometimes we do not need to write one. We can extend native classes to get more out of them.

If you don’t know about iOS Swift extensions, learn about them here.

The main advantage of extensions maybe, for me at least is…

iOS extensions can also extend native classes

So, if you need an extra feature of an existing component/element or extend native class’s functionality, you’ll just have to write an extension for it. It can reside in any file existed in app. After you’re done declaring your extension, you can just use them as functions of that extended class everywhere.

Let’s start with some example to clarify my point.

Let’s say we need underlined labels. Paste this anywhere in your code.

Now, our UILabel class have a new function named underline available throughout the app. Let’s say we have a label like below,

We can use our underline class just by adding following line,

As we have extended our UIKit’s base UILabel class, we have our underline function available for every component that’s of UILabel class or extension of UILabel!

So our implementation would look something like this,

That’s a very basic example. But it can be very very powerful too!

Let’s have a look at another example, a more primitive one formatting wise, yet necessary nonetheless.

We need to format integer numbers with commas whenever we need to show say a large amount. If we want to comma format any integer number in our project we can just add an extra function extending our native Int class - like this,

Now we can utilize it like below anywhere we want in our code.

Isn’t that handy?

Now, what if it’s a currency amount? iOS have a handy formatter just for this use case. We can use that NumberFormatter class along with extensions to use this formatter globally just like our comma separator function we wrote extending Int class.

Let’s define another extension , but for this purpose we’re gonna extend our Double class, as currency is most likely to be a double type anyway!

Now, just use it like below and viola!

Of course, you can override the locale to get a different format of currency.

For that purpose, we’ll have to rewrite our function a little. First we need the locale string as a function parameter. We’re going to change this,

into this,

Here, the placeholder someString would get replaced with our locale string parameter I told you before.

So our changed function should now look something like this,

Now, if we use it, it’ll return formatted amount string with the locale specified by you.

See the convenience?

Now as we are done with formatting those pesky numbers, let’s turn our attention to color.

We can declare colors primarily like this,

That’s all good and dandy, but…

How many times you have found it irritating to declare colors with default iOS color initializer, when you get color codes as hex format?

In a real case scenario, declaring colors isn’t this much simple. In my case, I have always been given with hexadecimal values of colors to decorate my app which is the industry norm (black would be like #000000, red #FF0000 etc.)

.

.

.

If we want to use these in our code as colors, there is no direct solution at all. We can use utility sites like this, which gives the actual code for it to use with our native UIColor class.

.

.

Wouldn’t we be better off, if only we could use hex or RGB color codes directly in code?

The answer for devs like me is of course…

Yes Sire, please show me the divine path to integrate hex & RGB overrides….

Let’s see how we can do just that, with our fancy new knowledge of iOS swift extensions! We’ll extend our native UIColor class to add two convenience init functions, so that we can use UIColor to define colors with both hex and RGB values.

Add the extension below,

Now, we can define color values like below,

.

PRO DEV TIP:

We can also use extensions to revive some former functionality, that were available before in ObjC, but unavailable now in Swift.

With former NSError class, we used to get error code and domain for every errors. With Error class for swift , iOS somehow managed to forget to include error codes and domain in error responses.

Actually, our Error class is derived from former NSError class. We can write an extension for new Error class that we have - so we can use the code and domain variables of NSError, in our Error class.

The extension itself is somewhat miniscule though powerful in its own right!

Now we have code and domain variables available in every errors.

Textfield Padding

Are you one of those layout elites who have wrestled before to align a textfield with a top aligned label ?

Even if you have aligned them perfectly in your storyboard, it always gets set some point ahead of the top label upon render!

The solution to this is to set paddings to your textfield’s view. Now again, you discover a very disturbing fact while doing so.

There’s no padding setter to set paddings to UITextField’s view!!!

However, there’s a workaround to this problem. A textfield in iOS have two left and right views (one for each side), which can be used to set textfield left or right images or custom nibs/views. We can use these views as padding if we don’t use them for setting custom views for our textfields.

The extension is as following,

Now, we’re able to set padding only by,

Hide Input Keyboard On Tap

We all have faced this while developing app views with multiple input forms. Once a user taps a textfield to edit or enter values, a keyboard appears — which then said user uses to input values in the respective fields. Whenever the user taps outside keyboard area (i.e. on the background), the keyboard should disappear to reveal the background view.

But alas, that is not the normal behavior!

We have to use a gesture recognizer to look for tap on that view to dismiss our keyboard (remove focus from input).

So in our every view we want this behavior, we have to implement this gesture recognizer! To reduce our workload we can again reap the benefits of iOS extensions.

We’re gonna implement a gesture recognizer extending the native UIViewController class.

See the code below,

Our extension has two functions: hideKeyboardWhenTappedAround() merely adds a gesture recognizer with selector set to our second function dismissKeyboard(), which calls the view’s endEditing function with ‘true’ parameter. It results in the focus removal of all input on that view thus hiding the input keyboard.

So, to enable this behavior, we’ll just have to add the following line of code in our ViewController’s viewDidLoad() function.

And that’s it!

That’s all for now folks. Check out my other articles & tips here.

--

--

Mohaiminul Islam
InfancyIT

Software Engineer (iOS, Web) & a reclusive learner