Reputation: 33
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.
Upvotes: 3
Views: 873
Reputation: 3470
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.
Upvotes: 0
Reputation: 12303
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
}
}
Upvotes: 2