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:
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:
| Property | Type | Description |
|---|---|---|
text | String? | The text displayed by the label. |
attributedText | NSAttributedString? | Allows rich text formatting (e.g., mixed fonts, colors). |
font | UIFont | The font used for the label’s text. |
textColor | UIColor | The color of the text. |
textAlignment | NSTextAlignment | Alignment of text (e.g., .left, .center, .right). |
numberOfLines | Int | Number of lines for text (0 means unlimited). |
lineBreakMode | NSLineBreakMode | How text wraps or truncates (e.g., .byTruncatingTail, .byWordWrapping). |
adjustsFontSizeToFitWidth | Bool | Shrinks font size to fit the label’s width if true. |
minimumScaleFactor | CGFloat | Minimum scale factor for font size when adjustsFontSizeToFitWidth is true. |
shadowColor | UIColor? | Color of the text shadow. |
shadowOffset | CGSize | Offset of the shadow (width and height). |
isUserInteractionEnabled | Bool | Whether the label responds to user interactions (default: false). |
isEnabled | Bool | Whether the label is enabled (affects appearance, default: true). |
isHighlighted | Bool | Whether the label is highlighted (used with highlightedTextColor). |
highlightedTextColor | UIColor? | Text color when the label is highlighted. |
Example: Configuring Properties:
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 = .byWordWrappingKey Methods of UILabel
UILabel inherits many methods from UIView, but it also provides specific methods for text-related functionality:
| Method | Description |
|---|---|
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:
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:
- Set
adjustsFontSizeToFitWidthtotrue. - Specify a
minimumScaleFactor(between 0 and 1) to limit how much the font can shrink. - Optionally, set
numberOfLinesto control multi-line behavior.
Example:
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
minimumScaleFactoror 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:
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:
- Add the font file (e.g.,
.ttfor.otf) to your Xcode project. - Include the font in
Info.plistunderFonts provided by application(UIAppFonts). - Use the exact font name (check with
UIFont.familyNamesor font documentation).
Example: Debugging Font Names:
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:
- Set
shadowColorto aUIColor. - Set
shadowOffsetto aCGSizefor the shadow’s horizontal and vertical offset. - Optionally, adjust the label’s
layerproperties for advanced effects (e.g., blur).
Example: Basic Shadow:
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:
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:
shadowColorandshadowOffsetapply to the text only.- Layer-based shadows (
layer.shadow*) apply to the entire view, including the text and background. - Ensure
masksToBoundsisfalsefor layer shadows to be visible. - Shadows can impact performance if overused; test on target devices.
Best Practices
- Use Auto Layout: Set
translatesAutoresizingMaskIntoConstraints = falseand use constraints (e.g., with SnapKit orNSLayoutConstraint) to position labels. - Support Dynamic Type: Use
preferredFont(forTextStyle:)and setadjustsFontForContentSizeCategory = truefor accessibility. - Optimize Performance: Avoid excessive use of shadows or complex attributed text in table/collection views.
- Test Truncation: Ensure
lineBreakModeandnumberOfLineshandle long text gracefully. - Use Attributed Text for Complex Formatting: Combine fonts, colors, and styles with
NSAttributedString.
Example: Using Attributed Text:
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
textorattributedTextis 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 = falseandshadowOpacity > 0. - Text Truncating Unexpectedly: Check
numberOfLines,lineBreakMode, andadjustsFontSizeToFitWidth.
Example: Complete UILabel Setup
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)
}
}
}