Swift font.withSize not changing font size on UILabel
Asked Answered
D

2

7

I was having trouble changing font size in my project, so I made a playground. No matter where I put the font.withSize property, the simulator does not reflect the font size change.

import UIKit
import PlaygroundSupport

    class MyViewController : UIViewController {
        override func loadView() {
            let view = UIView()
            view.backgroundColor = .white

            let label = UILabel()
            label.font.withSize(80)
            label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
            label.text = "Hello Mom!"
            label.textColor = .black



            view.addSubview(label)
            self.view = view
        }
    }
Deformed answered 18/4, 2018 at 15:45 Comment(0)
E
25

withSize(_:) does not modify the font. It returns a new font with the same properties as the font you called it on, but with the new size. You have to assign the label's font to it instead:

label.font = label.font.withSize(80)
Eichmann answered 18/4, 2018 at 15:50 Comment(0)
U
4

You cannot set the size of a UIFont.

UIFont.withSize() is an initializer and will return a new UIFont object with the same characteristics as the original but with the font size specified.

So you need to assign a new font with the correct size to your label. For your example, you could use:

label.font = label.font.withSize(80)

Undrape answered 18/4, 2018 at 16:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.