How to customise UILabel using SWIFT 4.0?

Requirements:

Operating System: OS X 10.9.4+

IDE: Xcode 9

Level: Beginner to intermediate.

We can use Storyboard and interface builder to change the look and feel of UILabel. However, sometime, we have no other way but do these customizations programmatically. One of the reasons to do so is to keep all the styles in one place. In other words, it’s something like css stylesheet that can render all pages or views. Whatever the reason is, let’s try it.

Open Xcode 9 and create a new project. A dialog box will appear for selecting template. Choose single view application and press next.

Screen Shot 2014-09-14 at 2.05.25 PM

In the next box, type Product name – “Custom Label”. In Organization Identifier box, type reverse of your domain name. Choose Swift as language and press next.

 

customLabel1

From next dialog box select the location where you want to save the project and press “Create” button.

Screen Shot 2014-09-14 at 2.11.39 PM

Now open Main.storyboard from Project Navigator (If you can’t see project navigator in the left side of the screen, press Commad+O). You will see a blank View Controller in the workspace window.

 

customLabel2

Drag and drop a Label element from Utilities panel (If you can’t see Utilities Panel, press Command+Option+0) to the View Controller of the workspace (See above figure – bottom right corner).

Press Command+N (or File > New > File) to add a new file to the project. From template chooser box select Swift file and press next.Screen Shot 2014-09-14 at 2.24.46 PM

Save the file as MyCustomLabel.

customLabel3

Open MyCustomLabel.swift file.

import UIKit so that you can subclass MyCustomLabel class from UILabel.

import UIKit

Write a new subclass of UILabel and name it “MyCustomLabel”

class MyCustomLabel: UILabel {

}

We’ve to override init(coder aDecoder: NSCoder!)  function.

init(coder aDecoder: NSCoder!) {

super.init(coder: aDecoder)

}

The colour of the text that we write inside the UILabel can be changed as follows:

self.textColor = UIColor.blue

Finally, our whole code will look like :

Now, you’ve to attach this custom class with your Label. Let’s do them in 3 steps.

Go to Storyboard and select the label.

From Utility panel select the Identity Inspector.

In the class box Type MyCustomLabel

customLabel4

To see what you have done, press Command+R (or Product > Run) to run the application on simulator