Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different UIFont sizes for different iOS devices in Swift

I'm developing swift based iOS application for iPhone family. My application supports all devices start from iPhone 4s to iPhone X. Labels appears bigger in smaller devices like iPhone 4s as I added bigger font size for high end devices. Can someone help me on how to scale the font according to device. I tried size classes with compact/regular width and compact/regular height but none of them helped me. Your help is very much appreciated

Storyboard font setting Rendering app on different devices

like image 231
Bharath Vankireddy Avatar asked Sep 16 '25 12:09

Bharath Vankireddy


1 Answers

Programmatically

Without using the storyboard I have the approach to simply change the font size depending on the screen width like so:

func dynamicFontSize(_ FontSize: CGFloat) -> CGFloat {
    let screenWidth = UIScreen.main.bounds.size.width
    let calculatedFontSize = screenWidth / 375 * FontSize
    return calculatedFontSize
}

and can be used as:

myLabel.font = UIFont(name: "Helvetica", size: dynamicFontSize(20))

Note that in the dynamicFontSize function the number 375 is simply the basis for the font size calculation, because I usually test my app on iPhone 8 (i.e. font size 18 is actually 18 on an iPhone 8 due to its actual width of 375). This number can be altered to your liking.

Storyboard

If you insist on using storyboard, you can instead create a new swift file subclassing UILabel and use an @IBInspectable like so:

import UIKit

class UILabelFontClass: UILabel {

    @IBInspectable var DynamicFontSize: CGFloat = 0 {
        didSet {
            overrideFontSize(FontSize: DynamicFontSize)
        }
    }

    func overrideFontSize(FontSize: CGFloat){
        let fontName = self.font.fontName
        let screenWidth = UIScreen.main.bounds.size.width
        let calculatedFontSize = screenWidth / 375 * FontSize
        self.font = UIFont(name: fontName, size: calculatedFontSize)
    }
}

Inside storyboard subclass UILabelFontClass to your label: Subclassing_UILabelFontClass

And now in the Attributes inspector, you can set the font size: Attributes_inspector_set_fontsize

like image 85
Caravan Avatar answered Sep 18 '25 09:09

Caravan