How To Add Dynamic Font Size about Multi Device in

2019-03-21 21:23发布

问题:

I added autoLayout in storyBoard (w: Any, h: Any)

But because of fixed font size, The font size is same in all of devices (4, 4.7, 5.5 inch)

It looks nice in 4 inch. But in 5.5 inch, That's too small

I want to dynamically inclease and decrease UIlabel font size in any devices.

Any Ideas?

回答1:

I Found Solution

I Made one Class

class UILabelDeviceClass : UILabel {

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

func overrideFontSize(fontSize:CGFloat){
    let currentFontName = self.font.fontName
    var calculatedFont: UIFont?
    let bounds = UIScreen.mainScreen().bounds
    let height = bounds.size.height
    switch height {
    case 480.0: //Iphone 3,4,SE => 3.5 inch
        calculatedFont = UIFont(name: currentFontName, size: fontSize * 0.7)
        self.font = calculatedFont
        break
    case 568.0: //iphone 5, 5s => 4 inch
        calculatedFont = UIFont(name: currentFontName, size: fontSize * 0.8)
        self.font = calculatedFont
        break
    case 667.0: //iphone 6, 6s => 4.7 inch
        calculatedFont = UIFont(name: currentFontName, size: fontSize * 0.9)
        self.font = calculatedFont
        break
    case 736.0: //iphone 6s+ 6+ => 5.5 inch
        calculatedFont = UIFont(name: currentFontName, size: fontSize)
        self.font = calculatedFont
        break
    default:
        print("not an iPhone")
        break
    }

}

}

Then, Set Class

And Then, Set Value

Happy Coding!



回答2:

Check the screen size and manipulate the font size based on it:

let screenSize = UIScreen.mainScreen().bounds.size

if screenSize.height < 568 {
    //Set font size for 4
} else if screenSize.height < 568 {
    //Set font size for 5
} else if screenSize.height < 568 {
    //Set font size for 6
} else {
    //Set font size for 6+
}

UPDATE:

Extend the UILabel class to setup your label:

extension UILabel { 
    func setupLabelDynamicSize(size size:CGFloat) {
        let screenSize = UIScreen.mainScreen().bounds.size

        if screenSize.height < 568 {
            //Set self.font equal size
        } else if screenSize.height < 568 {
            //Set self.font equal size + 1
        } else if screenSize.height < 568 {
            //Set self.font equal size + 2
        } else {
            //Set self.font equal size + 3
        }
    }
}

then wherever you have a label that you want with dynamic size just call:

labelObject.setupLabelForDynamicSize(size: 14)


回答3:

No, you can't config size class for iPhone 5.5 only. Size class can not distinguish iPhone 5, 6 vs 6Plus.

Only 1 edge case supports for iPhone 5.5 landscape only: regular width, compact height: 5.5" iPhone in Landscape

The only way you can do it is check device size in you code !



回答4:

WIth xcode 7.3, you can click add '+' in Attributes inspector to select font size each device