chieudai14kytu chieudai14kytu - 3 months ago 18
Swift Question

Button frame change at runtime

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.

Answer

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
    }
}
Comments