UILabel subclass appearance in Storyboard
Asked Answered
R

1

5

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)
    }
}
Runge answered 4/1, 2016 at 14:49 Comment(0)
O
9

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.

Orchidectomy answered 4/1, 2016 at 17:22 Comment(2)
Super! Thanks! Hope your answer will help someone else as well.Runge
Thanks it works, but if it possible to change the default font in Attributes inspector?Ivar

© 2022 - 2024 — McMap. All rights reserved.