iosswiftxcodefontsswift4.2

Swift 4 iOS - Completely override system font without compromising storyboard font size


I would like to:

  1. override the default font in all the application choosing the font size from the storyboard
  2. if possibile see a preview of the custom font in the text visualized in the storyboard.

I managed to insert the custom font but I have problems in the texts sizing.

I tried the following solutions but they still don't completely fit my requirements:

  1. Added this row in the AppDelegate inside the didFinishLaunchingWithOptions func:
    UILabel.appearance().font = UIFont(name: "yourFont", size: yourSize)
    this overrides font for all UILabels but it overrides the font size too. All labels comes with the same yourSize font size.
  2. I extended the UILabel forcing it executing changeFontName.

    extension UILabel {
        override open func awakeFromNib() {
            super.awakeFromNib()
            changeFontName()
        }
    
        func changeFontName() {
            self.font = UIFont(name: "yourFont", size: self.font.pointSize)
        }
    }
    

    This is working but storyboard obviously does not update the view. And I'm not sure that it is the proper way of doing it


Solution

  • The solution I approached it's similar to the #2 solution but it renders the font on the storyboard too.

    We created some classes that extend the default UIViews, for example for UILabel and UIButton. You can do something like this:

    @IBDesignable
    public class CustomUILabel: UILabel {
    
        public override func awakeFromNib() {
            super.awakeFromNib()
            configureLabel()
        }
    
        public override func prepareForInterfaceBuilder() {
            super.prepareForInterfaceBuilder()
            configureLabel()
        }
    
        func configureLabel() {
            font = UIFont(name: "MyCustomFont", size: self.font.pointSize)
        }
    
    }
    
    @IBDesignable
    public class CustomUIButton: UIButton {
    
        public override func awakeFromNib() {
            super.awakeFromNib()
            configureLabel()
        }
    
        public override func prepareForInterfaceBuilder() {
            super.prepareForInterfaceBuilder()
            configureLabel()
        }
    
        func configureLabel() {
            titleLabel?.font = UIFont(name: "MyCustomFont", size: self.titleLabel!.font.pointSize)
        }
    
    }
    

    Then in the storyboard we set in the Identity Inspector that class as Custom Class to each component that had to change the font.

    It is not the most clean solution, but at least if you change the MyCustomFont font in the whole application you can just change it by code in one single shot.