A UILabel subclass that pads its text with contentInset. The inset is included in intrinsicContentSize, so Auto Layout reserves the padding without extra constraints.
- Drop-in
UILabel— text, attributed text, alignment, fonts, andnumberOfLineswork as usual - Intrinsic size —
contentInsetis part of the label's intrinsic width and height - Drawing — text is drawn inside the inset area, leaving the padding empty
- Live updates — changing
contentInsetinvalidates the intrinsic content size
- iOS 11.0+
- Swift 5.0+
pod 'EdgeInsetLabel'Then run:
pod installIn Xcode: File → Add Packages… and enter:
https://github.com/iLiuChang/EdgeInsetLabel.git
Or add it to your Package.swift:
dependencies: [
.package(url: "https://github.com/iLiuChang/EdgeInsetLabel.git", from: "1.1.0")
]- Download
Sources/EdgeInsetLabel.swift - Drag it into your Xcode project
import EdgeInsetLabel
let label = EdgeInsetLabel()
label.text = "Hello"
label.textColor = .white
label.backgroundColor = .systemBlue
label.contentInset = UIEdgeInsets(top: 8, left: 12, bottom: 8, right: 12)With Auto Layout, the label's intrinsic size is the text size plus contentInset. Pin it as you would any other label and the padding is already included.
Multiline text is measured inside the inset bounds:
label.numberOfLines = 0
label.contentInset = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)Change the inset later and the intrinsic size updates:
label.contentInset = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8)Open Demo/EdgeInsetLabel.xcodeproj and run it. The sample edits the label text from a text field and contentInset from a slider.
| Property / Method | Description |
|---|---|
contentInset |
Space reserved around the text, inside the label bounds. Included in intrinsicContentSize. Defaults to .zero. |
textRect(forBounds:limitedToNumberOfLines:) |
Measures the text inside the inset bounds, then expands the rect so the result includes the padding. |
drawText(in:) |
Draws the text in rect inset by contentInset. The padding stays empty. |
EdgeInsetLabel overrides the two UILabel methods that decide where text is measured and drawn.
textRect(forBounds:limitedToNumberOfLines:) shrinks the proposed bounds by contentInset, asks UILabel for the text rect, then adds the inset back. intrinsicContentSize goes through this method, so Auto Layout sees the padding.
drawText(in:) draws into the same inset rect. The area between the text and the label bounds is left empty and shows the label's background.
MIT License. See LICENSE for details.