Reputation: 387
The following code works on an iPhone but on an iPad the circle is not evenly rounded.
How can I make the view look like a circle on both devices?
let width:CGFloat = UIScreen.main.bounds.width*0.0533
label.layer.masksToBounds = true
label.layer.cornerRadius = width/2
Upvotes: 10
Views: 13438
Reputation: 1
I have found out that to make the uiview circle appart from just .frame.size.height / 2 , width and height of the uiview should be equal.
Upvotes: 0
Reputation: 6862
One reason this can happen is if auto layout is changing the size of the label because of a constraint conflict.
Check the debug console to see if thats happening, or just use the "Debug View Hierarchy" to see the actual dimensions of the view.
Upvotes: 3
Reputation: 647
If you want your UIView to appear as a circle there are couple of ways doing this.
If you don't know the height/width of your view in advance. You can simply override layoutSubviews()
function in it's superview class or func viewDidLayoutSubviews()
function in view controller and set the corner radius directly there.
override func layoutSubviews() {
super.layoutSubviews()
label.layer.cornerRadius = label.frame.size.width/2
}
Don't forget to set the UIView's layer's masksToBounds property to true.
Specify bezier path for the mask layer. Layer's frame must be updated every time the view changes its size.
If you're dealing with images, you can also consider rounding the image itself before displaying it in UIImageView - performance wise it could be a way faster than the previous options.
Upvotes: 11
Reputation: 131
For making complete circle, you should keep height and width same for your label. Use this code.
let width:CGFloat = UIScreen.main.bounds.width*0.0533
label.frame = CGRect(0,0,width,width)
label.layer.masksToBounds = true
label.layer.cornerRadius = width/2
Upvotes: 8