【问题标题】:Set different font as per title and subtitle in UIlabel IBDesignable根据 UIlabel IBDesignable 中的标题和副标题设置不同的字体
【发布时间】:2019-05-27 14:18:27
【问题描述】:

我使用以下代码为 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 创建不同的扩展

【问题讨论】:

    标签: ios fonts uilabel ibdesignable


    【解决方案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
    

    【讨论】:

    • 关于通过情节提要中的属性检查器设置样式的任何首选建议?
    猜你喜欢
    • 2011-09-03
    • 2018-06-25
    • 2012-12-27
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多