Search code examples
iosswiftuilabel

ios - Can we change Font, Size for all Label by single code / file?


I would like to ask, have any ways to change all Font, Size for Label by single code? Like Dynamic Type inside the app. ex: Android have been supported with the XML file (dimens)

Thank you!


Solution

  • There are a few ways to achieve that

    1. You can do something like this to give the same styling for all UILabels:
    extension UILabel {
        @nonobjc
        convenience init() {
            self.init(frame: .zero)
            self.font = UIFont.systemFont(ofSize: 12, weight: UIFontWeightThin)
            //... here goes other changes
        }
    }
    

    You will need to use a convenience init every time.

    1. Another option would be to create some custom UILabel:
    class CustomLabel: UILabel {
        override init(frame: CGRect) {
            super.init(frame: frame)
            self.font = UIFont.systemFont(ofSize: 12, weight: UIFontWeightThin)
            //... here goes other changes
        }
    
        required init?(coder: NSCoder) {
            super.init(coder: coder)
            self.font = UIFont.systemFont(ofSize: 12, weight: UIFontWeightThin)
            //... here goes other changes
        }
    }
    
    1. The last option is relatively more complex and will require you to create customised way of handling different stylings for UILabel.