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.
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 constructorUILabel()
.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:
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 aString
) 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.