Monday, April 1, 2019

Swift: Dynamically Change A Label's Font Size Based On Device's Screen Size

Different devices have different screen sizes or resolutions, for example, iPhone SE has 640x1136 resolution (pixels) but iPhone 6 has 750x1334 resolution (pixels). We can use UIKit framework to obtain information about the screen resolutions.

Points are logical unit used in iOS. The number of pixels per point varies from devices. The more pixels per point, the clearer the icons and texts.


When developing an app to run on different devices, the text's size must be able to dynamically change or the text might look fine on one device but looks too big or too small on another.

Below is a custom label in which its font can change based on the device's screen size.
    
import Foundation
import UIKit

public class AdaptiveFontLabel: UILabel {
    private let iphone6HeightInPoints:CGFloat = 667
    
    var utfText:String?
    
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        // On landscape mode, height is less than width
        let heightDiff = max(UIScreen.main.bounds.height, UIScreen.main.bounds.width) / iphone6HeightInPoints
        let newFontSize = font.pointSize * heightDiff
        
        font = UIFont(descriptor: font.fontDescriptor, size: newFontSize)
    }
    
    private func max(_ first:CGFloat, _ second:CGFloat) -> CGFloat {
        return first > second ? first : second
    }
}
    

The idea here is we need to test the label's font on a preferred device first to see it look ok. In my case, I chose iPhone 6, and the font size 21 looks perfect on it.

Then, I noted down the iPhone 6's screen size in points so that i can calculate the screen size difference (in points) between the iPhone 6 and the current device the app is running on. The font size is recalculated based on the screen difference.


No comments:

Post a Comment