Search code examples
iosfontsuilabelibdesignable

Set different font as per title and subtitle in UIlabel IBDesignable


I had created the custom class for uilabel with below code:

@IBDesignable
public class CustomUILabel: UILabel {

    public override func awakeFromNib() {
        super.awakeFromNib()
        configureLabel()
    }

    public override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        configureLabel()
    }

    func configureLabel() {
        textColor = .white
        font = UIFont(name: Constants.regularFontName, size: 14)
    }
}

This help me to set the font through out the application.But i wanted to create different bold font type for title and regular font for subtitle. Is this possible only with one file ? Or i need to create different Extension for that type of UIlabel


Solution

  • You could for example add a custom style property like this:

    @IBDesignable
    public class CustomUILabel: UILabel {
    
        enum CustomUILabelStyle {
            case title, subtitle
    
            var font: UIFont? {
                switch self {
                case .title:
                    return UIFont(name: Constants.boldFontName, size: 14)
                case .subtitle:
                    return UIFont(name: Constants.regularFontName, size: 14)
                }
            }
    
            var textColor: UIColor {
                switch self {
                // add cases if you want different colors for different styles
                default: return .white
                }
            }
        }
    
        var style: CustomUILabelStyle = .title {
            didSet {
                // update the label's properties after changing the style
                if style != oldValue {
                    configureLabel()
                }
            }
        }
    
        public override func awakeFromNib() {
            super.awakeFromNib()
            configureLabel()
        }
    
        public override func prepareForInterfaceBuilder() {
            super.prepareForInterfaceBuilder()
            configureLabel()
        }
    
        func configureLabel() {
            font = style.font
            textColor = style.textColor
        }
    
    }
    

    You use it like this:

    let label = CustomUILabel()
    label.style = .title
    // label.style = .subtitle