2

I have created a subclass of UILabel in Swift i want to customize some properties of label like fonts,color size etc based on which type of label it is.

This label is created in storyboard file. For identifying the type of labe i have created a custom property name 'labelType' this labelType will never change it's value once it has been assigned. So we should create this property is 'let' but the issue is we need to defined this property before it's initWithCoder is called.

How can we set it's inital value in initWithCoder dynamically ? (or any other default constructor ? )

currently i have make the property as var and i am setting that property's value from storyboard itself (User defined runtime attributes)

Here is the code

class BMLabel: UILabel {

    var labelType:NSNumber!
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }
    override func awakeFromNib() {
        self.setUpProperties()

    }
    func setUpProperties() {
        switch(labelType) {
        case 1:
            self.font = Constants.FONTS.LIST_UUID_FONT

Image of storyboard

Mihir Mehta
  • 13,743
  • 3
  • 64
  • 88
  • @IBDesignable is the thing you are looking for ,... – MOHAMMAD ISHAQ Dec 11 '15 at 05:47
  • nope it's not useful – Mihir Mehta Dec 11 '15 at 06:07
  • unfortunately, all properties must be initialized at super.init call. this behavior is discus from early stages of Swift as a bug with no correction until current version. reinitialization of var (as you did) is the best (or better to say easiest) known workaround for now. – user3441734 Dec 11 '15 at 07:01
  • If we use property which are not going to change during their lifetime as 'var' than that's unfortunate .... i still hope that there must be a way, a workaround ... – Mihir Mehta Dec 11 '15 at 07:07
  • to mimic read only property which looks like constant i use class C { private (set) var i = 0 init() {} } class D: C { // as read only computed property, it mimics constant value here var j: Int { return i } override init() { super.init() i = 10 } } – user3441734 Dec 11 '15 at 08:00
  • in other words let i = 10 is an semantic equivalent to var i: Int { return 10 } – user3441734 Dec 11 '15 at 08:13
  • still it won't be dynamic – Mihir Mehta Dec 11 '15 at 09:33
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/97608/discussion-between-user3441734-and-mihir-mehta). – user3441734 Dec 11 '15 at 10:03

0 Answers0