user3574603
user3574603

Reputation: 3618

Swift/Cocoa Touch: How do I centre dynamically resized text in a UILabel?

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.

Number 5 centred in view 5000 is not centred vertically

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

Answers (1)

Edy
Edy

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

Related Questions