Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel subclass appearance in 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:

public class MyUILabel : UILabel {
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.font = UIFont(name: Constants.DefaultFont, size: 30)
    }
}
like image 676
ssnielsen Avatar asked Jan 04 '16 14:01

ssnielsen


1 Answers

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.

like image 150
Rob Avatar answered Oct 02 '22 14:10

Rob