Jimmy Jimmy - 6 months ago 98
Swift Question

IOS - All font management in one place

I'm making an iOS app by Swift. I want to manage all font size and its style at one place like the below HTML code. In the below code, all I have to resize all fonts in the page is changing

body{font-size}
.

<style>
body{
font-size: 30px; /* change only here */
}
</style>

<body>
<div style="font-size: 1em">normal</div>
<div style="font-size: 2em">double</div>
</body>


I would like to know how to manage all fonts in an APP in iOS development.

Answer

If you're using Swift, you can create a UILabel extension:

extension UILabel {

    var substituteFontName : String {
        get { return self.font.fontName }
        set { self.font = UIFont(name: newValue, size: self.font.pointSize) }
    }

}

And then where you do your appearance proxying:

UILabel.appearance().substituteFontName = applicationFont

There is equivalent Objective-C code using UI_APPEARANCE_SELECTOR on a property with the name substituteFontName.

Addition

For the case where you'd want to set bold and regular fonts separately:

extension UILabel {

    var substituteFontName : String {
        get { return self.font.fontName }
        set { 
            if self.font.fontName.rangeOfString("Medium") == nil { 
                self.font = UIFont(name: newValue, size: self.font.pointSize)
            }
        }
    }

    var substituteFontNameBold : String {
        get { return self.font.fontName }
        set { 
            if self.font.fontName.rangeOfString("Medium") != nil { 
                self.font = UIFont(name: newValue, size: self.font.pointSize)
            }
        }
    }
}

Then for your UIAppearance proxies:

UILabel.appearance().substituteFontName = applicationFont
UILabel.appearance().substituteFontNameBold = applicationFontBold

Note: if you're finding that the bold substitution isn't working, it's possible the default font name doesn't contain "Medium". Switch out that string for another match as needed (thanks to Mason in the comments below) .