impression7vx
impression7vx

Reputation: 1873

Font Sizing Per Device Programmatically

I am attempting to alter the text of a UILabel such that the text looks exactly the same per device.

Label texts

Here, I have 4 different simulators: 8Plus, 7, 5s, XR in that order. As you can see the texts look different. On the first simulation, it's smaller than say the 3rd one. How can I make it scale and look the same for each device, i.e. the text respects the size of the box?

let label = UILabel(frame: button.bounds)
    label.text = "Done"
    label.minimumScaleFactor = 0.2
    label.textAlignment = .center
    label.textColor = .white
    label.font = UIFont(name: label.font.fontName, size: 20)
    label.adjustsFontSizeToFitWidth = true
    label.isUserInteractionEnabled = true

Upvotes: 0

Views: 40

Answers (1)

Robert Dresler
Robert Dresler

Reputation: 11210

On the first simulation, it's smaller than say the 3rd one.

No, it isn't. It just looks like that because screen of iPhone 5S (640x1136 points) is smaller then screen of let's say iPhone Xs (1125x2436). Also text looks small against its background since background has fixed constraints which cause its resizing on all devices.

In order your text looked similarly against its background on all screens, you would have to set UILabel's top, leading, bottom and trailing constraint equal to superview's (with custom constant)

enter image description here

... then as you did, set minimumScaleFactor for your label

So, if you set font size to 20, then maximum font size will be 20. If your label should be smaller (there wouldn't be enough space because of constraints you set), your label will have the biggest possible font size which you set as minimum scale factor.

Upvotes: 1

Related Questions