Reputation: 3618
I have a UILabel
that takes the size of its parent view.
I want the label text to resize to fit within the containing view.
override func draw(_ rect: CGRect) {
let fontSize = self.frame.size.height * 0.9
var font = UIFont.preferredFont(forTextStyle: .body).withSize(fontSize)
font = UIFontMetrics(forTextStyle: .body).scaledFont(for: font)
let label = UILabel()
label.textAlignment = .center
label.font = font
label.frame.size = self.frame.size
label.minimumScaleFactor = 0.1
label.numberOfLines = 1
label.adjustsFontSizeToFitWidth = true
label.text = "5"
addSubview(label)
}
The above works just how I want. The number 5 is displayed in the centre of the containing view. However if I set the text to something longer (for example: label.text = "5"
), its vertical position changes.
How do I ensure that, no matter the length of the string, the text will be centred vertically as well as horizontally.
Upvotes: 0
Views: 56
Reputation: 245
Add this line of code in your UILabel set up. Should work as expected. This will make the label to center vertically.
label.baselineAdjustment = .alignCenters
Upvotes: 2