首页 > 解决方案 > 根据 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 创建不同的扩展

标签: iosfontsuilabelibdesignable

解决方案


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

推荐阅读