Different UIFont sizes for different iOS devices in Swift

主宰稳场 提交于 2019-12-12 18:57:43

问题


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


回答1:


You can try label hight according to view in storyboard .

with this image reference i done with iPhone 5s screen size and give label hight equal to hight in multiplier 30/554




回答2:


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:

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



来源:https://stackoverflow.com/questions/50981319/different-uifont-sizes-for-different-ios-devices-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!