Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Add Dynamic Font Size about Multi Device in Xcode Story Board

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?

enter image description here

like image 373
Yoohogyun Avatar asked Dec 19 '22 15:12

Yoohogyun


2 Answers

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

Img1

Img2

And Then, Set Value

Happy Coding!

like image 140
Yoohogyun Avatar answered Dec 27 '22 11:12

Yoohogyun


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)
like image 30
Sam Avatar answered Dec 27 '22 10:12

Sam