Bright Future Bright Future - 1 month ago 14
iOS Question

Can't set CALayer's border color

I'm trying to customize the appearance of a UIButton, like this:

@IBOutlet weak var button: UIButton!

override func viewDidLoad() {
super.viewDidLoad()

button.layer.cornerRadius = button.frame.size.width / 2
button.layer.borderColor = UIColor.cyan.cgColor
button.layer.borderWidth = 1
}


However when I run it, it displays nothing but the text of the button, what could cause the problem?

Answer

The problem is that you are running this code too soon (in viewDidLoad). Your cornerRadius calculation depends upon calculateButton.frame, but its value is not known at this time. Move your code into viewDidLayoutSubviews and I think you will find that it works as you expect.

Comments