Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 602
chieudai14kytu Avatar asked Jun 08 '26 13:06

chieudai14kytu


1 Answers

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
    }
}
like image 60
Igor Avatar answered Jun 10 '26 07:06

Igor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!