UILabel subclass appearance in Storyboard

℡╲_俬逩灬. 提交于 2019-12-06 02:44:20

问题


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:

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

回答1:


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

}

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

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.



来源:https://stackoverflow.com/questions/34593734/uilabel-subclass-appearance-in-storyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!