How do I change the font size of a UILabel in Swift?


You can change the font size of a UILabel in Swift by setting the font property of the UILabel to a UIFont object with the desired point size.

Here is the code for the basic setup

import UIKit
class TestController: UIViewController {
    
    private let messageLabel = UILabel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initialSetup()
    }
    
    private func initialSetup() {
        
        // basic setup
        view.backgroundColor = .white
        navigationItem.title = "UILabel"
        
        // label customization
        messageLabel.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        messageLabel.numberOfLines = 0
        
        // adding the constraints to label
        view.addSubview(messageLabel)
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        messageLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        messageLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30).isActive = true
        messageLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -30).isActive = true
    }
}

Output

In the above output, you can see a label with the default font size.

Here's an example of changing the font size

messageLabel.font = UIFont.systemFont(ofSize: 20)

Output

In this example, the font size of messageLabel is set to 20 points. You can adjust the value of fontSize to change the font size accordingly.

You can change the font weight in addition to changing the font size. Here is an example

messageLabel.font = UIFont.systemFont(ofSize: 20, weight: .semibold)

Output

Another option is creating the UIFont with your font name and specific size

messageLabel.font = UIFont.init(name: "AmericanTypewriter", size: 20)

Output

In the above example, you have changed the custom font.

Conclusion

You can easily change the font size of a UILabel. The font property is used to assign a font with the size. You can also assign the custom font if you want. The UIFont.init(name: "font_name", size: font_size) method is used to provide a custom font with the size.

Updated on: 07-Sep-2023

515 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements