Changing the Font Size of a UILabel in Swift

Changing the Font Size of a UILabel in Swift

28 February 2025 Stephan Petzl Leave a comment Xcode

Adjusting the font size of a UILabel in Swift can be a straightforward task once you understand the correct methods to use. If you’ve encountered the issue where label.font.pointSize is read-only, you’re not alone. Here’s a comprehensive guide on how to change the font size effectively.

Methods to Change UILabel Font Size

There are multiple ways to change the font size of a UILabel. Below are the most recommended methods, which ensure that you maintain the font’s style and weight:

Using the Font Method

  • To change the font size while keeping the current font style, you can use the following code:
label.font = label.font.withSize(20)

This method keeps the font weight and style intact, simply adjusting the size to your specified point size.

Specifying a New Font

  • If you need to specify a different font altogether, use:
label.font = UIFont(name: "Helvetica Neue", size: 20.0)

This is useful when you want to change both the font type and size.

  • For system fonts, the following options are available:
  • 
    label.font = UIFont.systemFont(ofSize: 20.0)
    label.font = UIFont.boldSystemFont(ofSize: 20.0)
    label.font = UIFont.italicSystemFont(ofSize: 20.0)
            

    Custom Font Extensions

    • You can also create a custom extension to streamline font size changes:
    
    extension UILabel {
        func sizeFont(_ size: CGFloat) {
            self.font = self.font.withSize(size)
        }
    }
            

    Use this extension in your code as follows:

    myLabel.sizeFont(100)

    Best Practices

    When changing the font size, consider where in your code this change is made. Ideally, set the font size in the viewDidLayoutSubviews method, as it doesn’t need to change every time the view appears. This approach is efficient and maintains consistent UI behavior.

    Enhancing Your Development Workflow with Repeato

    When developing and testing iOS applications, ensuring consistent UI behavior across different devices and scenarios is crucial. This is where Repeato, a no-code test automation tool, can be incredibly beneficial. Repeato allows you to create, run, and maintain automated tests for iOS apps efficiently.

    Its test recorder feature quickly captures user interactions, making it ideal for verifying UI changes like font size adjustments. Furthermore, Repeato supports running command line scripts or JavaScript code, which can automate complex tasks related to UI testing. Learn more about how Repeato can streamline your testing processes here.

    Like this article? there’s more where that came from!