【问题标题】:UILabel subclass appearance in Storyboard故事板中的 UILabel 子类外观
【发布时间】:2016-01-04 14:49:23
【问题描述】:

我创建了一个名为 MyUILabel 的 UILabel 子类。唯一改变的是字体和字体大小。当我运行该应用程序时,它会按预期显示。但是,在情节提要中,会显示默认的 UILabel。有什么方法可以让 Storyboards 显示我的子类中的字体和字体大小?

MyUILabel:

public class MyUILabel : UILabel {
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.font = UIFont(name: Constants.DefaultFont, size: 30)
    }
}

【问题讨论】:

    标签: swift uikit interface-builder xcode-storyboard


    【解决方案1】:

    你可以把它变成@IBDesignable,然后实现prepareForInterfaceBuilder

    @IBDesignable
    public class MyUILabel: UILabel {
    
        public override func awakeFromNib() {
            super.awakeFromNib()
            configureLabel()
        }
    
        public override func prepareForInterfaceBuilder() {
            super.prepareForInterfaceBuilder()
            configureLabel()
        }
    
        func configureLabel() {
            font = UIFont(name: Constants.DefaultFont, size: 40)
        }
    
    }
    

    注意,当我实现init(coder:) 时,IB 不喜欢它,所以我把它移到了awakeFromNib

    还请注意,当您创建 @IBDesignable 类时,Apple 建议您为这个可设计的类创建一个单独的目标(例如“文件”-“新建”-“目标...”-“Cocoa Touch 框架”) .更多信息,请参见 WWDC 2014 视频What’s New in Interface Builder

    【讨论】:

    • 超级!谢谢!希望您的回答也能对其他人有所帮助。
    • 感谢它的工作,但是否可以更改属性检查器中的默认字体?
    猜你喜欢
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多