UILabel
Swift programming
iOS development
programmatic UI
Swift tutorials

How to create UILabel programmatically using Swift?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Creating a `UILabel` programmatically in Swift is a fundamental skill for iOS developers, as it allows you to effectively manage UI components without relying solely on Interface Builder. This article will guide you through the process, providing technical explanations, examples, and supplementary details.

Creating a UILabel Programmatically

In Swift, creating UI components programmatically involves defining a new instance of a UIKit component, configuring its properties, and adding it to a view hierarchy. Let's explore how to achieve this with a `UILabel`.

Step-by-Step Guide

Step 1: Initialize a UILabel

To create a `UILabel`, you first need to initialize it:

  • `text`: The text the label will display.
  • `textColor`: The color of the text. Here, it's set to black.
  • `font`: The font of the text. You can use built-in fonts or custom fonts.
  • `textAlignment`: Aligns the text within the label. Options include `.left`, `.right`, `.center`, or `.justified`.
  • `numberOfLines`: Determines how many lines the text can have. Setting it to `0` allows unlimited lines.
  • `translatesAutoresizingMaskIntoConstraints`: Set to `false` when using Auto Layout.
  • `view.addSubview(myLabel)`: Adds the label to the view hierarchy.
  • Constraints: Used to position the label. In this example, the label is centered in the view with a defined width and a minimum height.
  • `layer.cornerRadius`: Rounds the corners of the label.
  • `layer.masksToBounds`: Ensures the rounded corners are drawn by clipping the excess.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.