Swift
UILabel
text alignment
iOS development
user interface

Swift. UILabel text alignment

Interview Questions practice on Codemia

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

Browse interview questions

Introduction to UILabel in Swift

In the world of iOS development, the `UILabel` is one of the quintessential UI components used to display text on the screen. It is versatile, easy to use, and customizable, making it a staple for developers when creating user interfaces. One important aspect of customizing `UILabel` is text alignment, which can greatly affect the readability and aesthetics of text within an app.

Understanding Text Alignment in UILabel

Text alignment in `UILabel` determines how the text is positioned relative to the bounds of the label. By default, text in a `UILabel` is centered, but Swift allows developers to customize this alignment through a property called `textAlignment`.

Available Text Alignments

The text alignment for a `UILabel` can be set using the `NSTextAlignment` enumeration, which provides several options:

  • .left: Aligns the text to the left of the label. Suitable for left-to-right languages such as English.
  • .center: Centers the text within the label. This is the default alignment.
  • .right: Aligns the text to the right of the label. Useful for right-to-left languages.
  • .justified: Justifies text so that each line has the same length, with interspersed line breaks.
  • .natural: Aligns text based on the script of the text’s language. The default `natural` alignment is `.left`.

How to Set Text Alignment in UILabel

Setting the text alignment in Swift is straightforward. Here is a simple example demonstrating how to set each type of alignment:

  • Multiline Labels: When using the `.justified` alignment, ensure that the label’s `numberOfLines` property is more than 1. Single-line labels do not support justification effectively.
  • Dynamic Text Resizing: Adjust text alignment settings in tandem with dynamic type size and `adjustsFontSizeToFitWidth` to ensure consistent readability.

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.