根据 UIlabel IBDesignable 中的标题和副标题设置不同的字体

Set different font as per title and subtitle in UIlabel IBDesignable

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

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

这有助于我设置字体 application.But 我想为标题创建不同的粗体字体类型,为副标题创建常规字体。 这可能只适用于一个文件吗? 或者我需要为该类型的 UIlabel 创建不同的扩展

例如,您可以像这样添加自定义 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