在UIlabel IBDesignable

时间:2018-12-30 19:40:49

标签: ios fonts uilabel ibdesignable

我已经使用以下代码为uilabel创建了自定义类:

@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)
    }
}

这帮助我在整个应用程序中设置字体。但是我想为标题创建不同的粗体字体,为字幕创建常规字体。 只能使用一个文件吗? 或者我需要为该类型的UIlabel创建不同的扩展

1 个答案:

答案 0 :(得分:1)

例如,您可以像这样添加自定义style属性:

@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
    }

}

您可以这样使用它:

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