Lazy UILabel property of custom control

471 Views Asked by At

I want to be able to set the title of my custom control in interface builder and implement the title as a UILabel. I have created my properties thus:

@IBInspectable var titleText: String? {
    get {
        return title.text
    }
    set(newTitleText) {
        title.text = newTitleText
    }
}
@IBInspectable lazy var title: UILabel = UILabel.init()

Is this a good/recommended way to do this? I also want the control to layout the UILabel if the title text has been set and plan to do this by overriding layoutSubviews - again is this recommended or would you suggest a different pattern?

My ultimate aim is to be able to enable a designer to configure my control from IB and exposing the UILabel as a property that can be configured in IB would be my ideal.

2

There are 2 best solutions below

1
On

First, I don't think that you need to make your variable lazy here, also, if you want to create a new instance of UILabel, it's better to user the constructor UILabel().

Now, I am not sure if I understand correctly your question, but if I did, then you can expose your custom view properties (a string that represents your title label for example) to the Attributes Inspector.

You would do it like so:

@IBDesignable
class CustomView: UIView {

    @IBOutlet weak var titleLabel: UILabel!

    @IBInspectable var title: String? {
        didSet { self.titleLabel.text = title }
    }

}

To break up the code above :

First you make the class (your custom view) @IBDesignable so that it supports live preview in the Interface Builder. Then, inside your custom view class, you create a title property (which is a String) and make sure to make it @IBInspectable so that you can change this property later via the Attributes Inspector. Finally you add a property observer ( didSet ) so that the text property of your custom label is updated whenever you change the title property from the Attributes Inspector.

0
On

@IBInspectable can be used only with the following types:

Int
CGFloat
Double
String
Bool
CGPoint
CGSize
CGRect
UIColor
UIImage

So, no, you can not "expose a UILabel" for design-time manipulation.