iostypesdynamicxibuifont

How to use custom TextStyle in xib?


In code , I can define a UILabel has a dynamic font like this, and I change this body TextStyle font from default size to 30.

label.font = UIFontMetrics(forTextStyle: .body).scaledFont(for: UIFont.systemFont(ofSize: 30))

But in Xib , I can only use the default body TextStyle . Is there any way to change body TextStyle 's default configuration in xib?


Solution

  • You can achieve this with a custom label. I will use @IBDesignable and @IBInspectable to update the UI.

    1. Create your own custom label:
    @IBDesignable
    class BodyTextStyleLabel: UILabel {
        @IBInspectable var bodyTextStyleFontSize: CGFloat = 30 {
            didSet {
                //Default is .body as you mentioned
                self.font = UIFontMetrics(forTextStyle: .body)
                    .scaledFont(for: .systemFont(ofSize: bodyTextStyleFontSize))
            }
        }
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            setup()
        }
    
        required init?(coder: NSCoder) {
            super.init(coder: coder)
            setup()
        }
    
        private func setup() {
            bodyTextStyleFontSize = 30
        }
    }
    
    1. In XIB file, change your default label to the class that is defined above and the expected font size:

    enter image description here

    enter image description here