1

I have a nib/xib file with several Labels. Each label should obviously have a different text, but should all look the same. I therefore create a (very simple) CustomLabel class that inherits from UILabel:

import UIKit

class CustomLabel: UILabel {
    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.layer.cornerRadius = self.frame.size.width/2.0
        self.layer.backgroundColor = UIColor.blueColor().CGColor
    }
}

I then click on each label in Interface Builder and set each custom class to this "CustomLabel", but nothing is changing when I compile.

How do I correctly create and link custom elements?

nhgrif
  • 61,578
  • 25
  • 134
  • 173
user3607973
  • 345
  • 1
  • 5
  • 15
  • Try marking the class as `@IBDesignable` – nhgrif Apr 22 '15 at 00:46
  • 1
    Do you mean it doesn't change in the storyboard or when you run? – rdelmar Apr 22 '15 at 00:47
  • possible duplicate of [IB\_DESIGNABLE, IBInspectable -- Interface builder does not update](http://stackoverflow.com/questions/26674111/ib-designable-ibinspectable-interface-builder-does-not-update) – nhgrif Apr 22 '15 at 00:48
  • I can try, but I heard that IB_DESIGNABLE and IBInspectable is quite buggy in XCode 6.3. What I mean however is that it doesn't update when run. – user3607973 Apr 22 '15 at 08:01

2 Answers2

1

When you call the init, parts of the view might not be loaded yet. You might want to do your view setup in

override public func awakeFromNib()
{
    super.awakeFromNib()
    self.layer.cornerRadius = self.frame.size.width/2.0
    self.layer.backgroundColor = UIColor.blueColor().CGColor
}

Cheers!

yairsz
  • 438
  • 5
  • 15
  • 1
    Like @yairsz said, awakeFromNib is the place to put that code. However, per Apple's documentation (albeit AppKit documentation), "You should call the super implementation of awakeFromNib only if you know for certain that your superclass provides an implementation." So if your super class doesn't provide it, don't call super.awakFromNib(). And you may also not need it to be public, but that's for you to decide for your specific needs. – BJ Miller Apr 22 '15 at 03:34
0

The problem I had was that I didn't call self.layer.masksToBounds = true (Giving UIView rounded corners, thus the rounded corner was not showing. I still don't understand why self.layer.backgroundColor doesn't have any effect though.

Community
  • 1
  • 1
user3607973
  • 345
  • 1
  • 5
  • 15