Skip to content

UILabel and Its Properties

UILabel is a fundamental UIKit class used to display text in an iOS app’s user interface. It is a subclass of UIView and provides a flexible way to present static or dynamic text with customizable appearance and behavior. This document covers the key properties and methods of UILabel, along with specific sections on adjusting font size, changing fonts, and applying shadows.

Overview of UILabel

A UILabel is used to display read-only text, such as titles, descriptions, or captions. It supports single-line or multi-line text, various font styles, colors, alignments, and other formatting options. Labels are lightweight and optimized for displaying text without user interaction (unlike UITextField or UITextView, which support editing).

Creating a UILabel

You can create a UILabel programmatically or via Interface Builder (storyboards/xibs).

Programmatic Example:

swift
import UIKit

let label = UILabel()
label.text = "Hello, UIKit!"
label.textAlignment = .center
view.addSubview(label)

Key Properties of UILabel

Below are the most commonly used properties of UILabel:

PropertyTypeDescription
textString?The text displayed by the label.
attributedTextNSAttributedString?Allows rich text formatting (e.g., mixed fonts, colors).
fontUIFontThe font used for the label’s text.
textColorUIColorThe color of the text.
textAlignmentNSTextAlignmentAlignment of text (e.g., .left, .center, .right).
numberOfLinesIntNumber of lines for text (0 means unlimited).
lineBreakModeNSLineBreakModeHow text wraps or truncates (e.g., .byTruncatingTail, .byWordWrapping).
adjustsFontSizeToFitWidthBoolShrinks font size to fit the label’s width if true.
minimumScaleFactorCGFloatMinimum scale factor for font size when adjustsFontSizeToFitWidth is true.
shadowColorUIColor?Color of the text shadow.
shadowOffsetCGSizeOffset of the shadow (width and height).
isUserInteractionEnabledBoolWhether the label responds to user interactions (default: false).
isEnabledBoolWhether the label is enabled (affects appearance, default: true).
isHighlightedBoolWhether the label is highlighted (used with highlightedTextColor).
highlightedTextColorUIColor?Text color when the label is highlighted.

Example: Configuring Properties:

swift
let label = UILabel()
label.text = "Welcome to UIKit"
label.font = UIFont.systemFont(ofSize: 18, weight: .bold)
label.textColor = .systemBlue
label.textAlignment = .center
label.numberOfLines = 2
label.lineBreakMode = .byWordWrapping

Key Methods of UILabel

UILabel inherits many methods from UIView, but it also provides specific methods for text-related functionality:

MethodDescription
sizeToFit()Resizes the label to fit its content (based on text and font).
textRect(forBounds:limitedToNumberOfLines:)Returns the bounding rectangle for the label’s text.
attributedTextRect(forBounds:limitedToNumberOfLines:)Returns the bounding rectangle for attributed text.
drawText(in:)Draws the label’s text in the specified rectangle (used in custom drawing).

Example: Using sizeToFit:

swift
let label = UILabel()
label.text = "Dynamic Text"
label.font = UIFont.systemFont(ofSize: 16)
label.sizeToFit() // Adjusts frame to fit text
view.addSubview(label)

Adjusting Font Size of UILabel to Fit Its Width

To make the text of a UILabel fit within its bounds without truncation, you can enable adjustsFontSizeToFitWidth and set a minimumScaleFactor. This automatically reduces the font size until the text fits the label’s width.

Steps:

  1. Set adjustsFontSizeToFitWidth to true.
  2. Specify a minimumScaleFactor (between 0 and 1) to limit how much the font can shrink.
  3. Optionally, set numberOfLines to control multi-line behavior.

Example:

swift
let label = UILabel()
label.text = "This is a very long text that needs to fit"
label.font = UIFont.systemFont(ofSize: 20)
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5 // Font can shrink to 50% of original size
label.numberOfLines = 1
view.addSubview(label)

// Set frame or constraints
label.frame = CGRect(x: 20, y: 100, width: 200, height: 40)

Notes:

  • Works best for single-line labels (numberOfLines = 1).
  • Ensure the label has a defined width (via frame or Auto Layout constraints).
  • The text will scale down until it reaches the minimumScaleFactor or fits the width.

Changing the Font of a UILabel

You can change the font of a UILabel using the font property, which accepts a UIFont object. UIKit provides system fonts, custom fonts, or dynamic type fonts for accessibility.

Options for Fonts:

  • System Fonts: UIFont.systemFont(ofSize:weight:), UIFont.boldSystemFont(ofSize:), etc.
  • Custom Fonts: Register a custom font file in your project and use UIFont(name:size:).
  • Dynamic Type: Use UIFont.preferredFont(forTextStyle:) for fonts that adapt to user accessibility settings.

Example: Changing Font:

swift
let label = UILabel()
label.text = "Styled Text"

// System font
label.font = UIFont.systemFont(ofSize: 18, weight: .medium)

// Custom font (ensure font is added to project and Info.plist)
label.font = UIFont(name: "HelveticaNeue-Bold", size: 18)

// Dynamic Type font
label.font = UIFont.preferredFont(forTextStyle: .body)
label.adjustsFontForContentSizeCategory = true // Supports Dynamic Type scaling
view.addSubview(label)

Adding a Custom Font:

  1. Add the font file (e.g., .ttf or .otf) to your Xcode project.
  2. Include the font in Info.plist under Fonts provided by application (UIAppFonts).
  3. Use the exact font name (check with UIFont.familyNames or font documentation).

Example: Debugging Font Names:

swift
for family in UIFont.familyNames {
    print(family, UIFont.fontNames(forFamilyName: family))
}

Applying a Shadow to a UILabel

You can add a shadow to a UILabel’s text using the shadowColor and shadowOffset properties. For more advanced shadow effects, you can use the label’s layer property (from UIView).

Steps for Basic Shadow:

  1. Set shadowColor to a UIColor.
  2. Set shadowOffset to a CGSize for the shadow’s horizontal and vertical offset.
  3. Optionally, adjust the label’s layer properties for advanced effects (e.g., blur).

Example: Basic Shadow:

swift
let label = UILabel()
label.text = "Shadowed Text"
label.textColor = .black
label.shadowColor = .gray
label.shadowOffset = CGSize(width: 2, height: 2)
view.addSubview(label)

Example: Advanced Shadow with Layer:

swift
let label = UILabel()
label.text = "Advanced Shadow"
label.textColor = .black
label.layer.shadowColor = UIColor.black.cgColor
label.layer.shadowOffset = CGSize(width: 3, height: 3)
label.layer.shadowOpacity = 0.5
label.layer.shadowRadius = 4.0
label.layer.masksToBounds = false // Required for shadow to appear outside bounds
view.addSubview(label)

Notes:

  • shadowColor and shadowOffset apply to the text only.
  • Layer-based shadows (layer.shadow*) apply to the entire view, including the text and background.
  • Ensure masksToBounds is false for layer shadows to be visible.
  • Shadows can impact performance if overused; test on target devices.

Best Practices

  • Use Auto Layout: Set translatesAutoresizingMaskIntoConstraints = false and use constraints (e.g., with SnapKit or NSLayoutConstraint) to position labels.
  • Support Dynamic Type: Use preferredFont(forTextStyle:) and set adjustsFontForContentSizeCategory = true for accessibility.
  • Optimize Performance: Avoid excessive use of shadows or complex attributed text in table/collection views.
  • Test Truncation: Ensure lineBreakMode and numberOfLines handle long text gracefully.
  • Use Attributed Text for Complex Formatting: Combine fonts, colors, and styles with NSAttributedString.

Example: Using Attributed Text:

swift
let label = UILabel()
let attributedString = NSMutableAttributedString(
    string: "Bold and Colored",
    attributes: [.font: UIFont.boldSystemFont(ofSize: 16)]
)
attributedString.addAttribute(
    .foregroundColor,
    value: UIColor.systemRed,
    range: NSRange(location: 0, length: 4)
)
label.attributedText = attributedString
view.addSubview(label)

Troubleshooting

  • Text Not Displaying: Ensure text or attributedText is set, and the label’s frame or constraints provide enough space.
  • Font Not Applied: Verify the font name for custom fonts or check if the font file is correctly included.
  • Shadow Not Visible: For layer shadows, ensure masksToBounds = false and shadowOpacity > 0.
  • Text Truncating Unexpectedly: Check numberOfLines, lineBreakMode, and adjustsFontSizeToFitWidth.

Example: Complete UILabel Setup

swift
import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let label = UILabel()
        label.text = "Styled UILabel Example"
        label.font = UIFont.preferredFont(forTextStyle: .headline)
        label.textColor = .systemBlue
        label.textAlignment = .center
        label.numberOfLines = 0
        label.adjustsFontSizeToFitWidth = true
        label.minimumScaleFactor = 0.7
        label.shadowColor = .gray
        label.shadowOffset = CGSize(width: 1, height: 1)
        
        view.addSubview(label)
        
        // Auto Layout with SnapKit (assuming SnapKit is included)
        label.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(200)
        }
    }
}

Resources

Released under the MIT License.