3

I have a subclass of UIButton:

class ColorButton: UIButton {
    override func awakeFromNib() {
        self.layer.backgroundColor = UIColor.blackColor().CGColor
        self.layer.cornerRadius = frame.size.width / 2
        self.clipsToBounds = true
    }
}

In interface builder, I set the button with 4 constraints: width = 100, height = 100, centerX, centerY. The button disappears when I run my code on the simulator. However, if it set

self.layer.cornerRadius = 50

it works. I cannot figure it out. If anybody understand this problem, please tell me.

monchote
  • 3,440
  • 2
  • 20
  • 20

2 Answers2

2

Add in awakeFromNib first line:

self.layoutIfNeeded()

Code:

class ColorButton: UIButton {
    override func awakeFromNib() {
        self.layoutIfNeeded()
        self.layer.backgroundColor = UIColor.blackColor().CGColor
        self.layer.cornerRadius = frame.size.width / 2
        self.clipsToBounds = true
    }
}
Igor
  • 12,165
  • 4
  • 57
  • 73
0

Your code works just fine in a fresh project so I suspect the problem is somewhere else. You forgot to call super.awakeFromNib() though. From Apple docs:

You must call the super implementation of awakeFromNib to give parent classes the opportunity to perform any additional initialization they require. Although the default implementation of this method does nothing, many UIKit classes provide non-empty implementations. You may call the super implementation at any point during your own awakeFromNib method.

enter image description here

monchote
  • 3,440
  • 2
  • 20
  • 20