UILabel子类出现在Storyboard中 [英] UILabel subclass appearance in Storyboard

查看:84
本文介绍了UILabel子类出现在Storyboard中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个名为MyUILabel的UILabel子类。唯一改变的是字体和字体大小。当我运行应用程序时,它看起来像预期的那样但是,在故事板中,显示了默认的UILabel。有没有办法让Storyboard显示我的子类的字体和字体大小?

I have created a subclass of UILabel called MyUILabel. The only thing changed is the font and font-size. It appears as expected when I run the app. However, the in the Storyboard, the default UILabel is showed. Is there any way to make Storyboards show the font and font-size from my subclass?

MyUILabel:

MyUILabel:

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


推荐答案

您可以将其设为 @IBDesignable ,然后实现 prepareForInterfaceBuilder

You could make it @IBDesignable, and then implement 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)
    }

}

注意,IB没有'当我实现 init(编码器:) 时,我喜欢它,所以我把它移到 awakeFromNib

Note, IB didn't like it when I implemented init(coder:), so I moved it into awakeFromNib.

另请注意,当您创建 @IBDesignable 类时,Apple会建议您创建单独的目标(例如,这个可设计的类的文件 - 新 - 目标...... - 可可触摸框架)。有关详细信息,请参阅WWDC 2014视频 Interface Builder中的新增功能

Also note that when you make an @IBDesignable class, Apple advises that you create a separate target (e.g. "File" - "New" - "Target..." - "Cocoa Touch Framework") for this designable class. For more information, see WWDC 2014 video What’s New in Interface Builder.

这篇关于UILabel子类出现在Storyboard中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆