Giving UIView rounded corners
Try this
#import <QuartzCore/QuartzCore.h> // not necessary for 10 years now :)
...
view.layer.cornerRadius = 5;
view.layer.masksToBounds = true;
Note: If you are trying to apply rounded corners to a UIViewController
's view, it should not be applied in the view controller's constructor, but rather in -viewDidLoad
, after view
is actually instantiated.
Swift
Short answer:
myView.layer.cornerRadius = 8
myView.layer.masksToBounds = true // optional
Supplemental Answer
If you have come to this answer, you have probably already seen enough to solve your problem. I'm adding this answer to give a bit more visual explanation for why things do what they do.
If you start with a regular UIView
it has square corners.
let blueView = UIView()
blueView.frame = CGRect(x: 100, y: 100, width: 100, height: 50)
blueView.backgroundColor = UIColor.blueColor()
view.addSubview(blueView)
You can give it round corners by changing the cornerRadius
property of the view's layer
.
blueView.layer.cornerRadius = 8
Larger radius values give more rounded corners
blueView.layer.cornerRadius = 25
and smaller values give less rounded corners.
blueView.layer.cornerRadius = 3
This might be enough to solve your problem right there. However, sometimes a view can have a subview or a sublayer that goes outside of the view's bounds. For example, if I were to add a subview like this
let mySubView = UIView()
mySubView.frame = CGRect(x: 20, y: 20, width: 100, height: 100)
mySubView.backgroundColor = UIColor.redColor()
blueView.addSubview(mySubView)
or if I were to add a sublayer like this
let mySubLayer = CALayer()
mySubLayer.frame = CGRect(x: 20, y: 20, width: 100, height: 100)
mySubLayer.backgroundColor = UIColor.redColor().CGColor
blueView.layer.addSublayer(mySubLayer)
Then I would end up with
Now, if I don't want things hanging outside of the bounds, I can do this
blueView.clipsToBounds = true
or this
blueView.layer.masksToBounds = true
which gives this result:
Both clipsToBounds
and masksToBounds
are equivalent. It is just that the first is used with UIView
and the second is used with CALayer
.
See also
- How to add borders and shadow
- Bezier paths
- Transformations
You can also use the User Defined Runtime Attributes feature of interface builder to set the key path layer.cornerRadius
to a value. Make sure you include the QuartzCore
library though.
This trick also works for setting layer.borderWidth however it will not work for layer.borderColor
as this expects a CGColor
not a UIColor
.
You will not be able to see the effects in the storyboard because these parameters are evaluated at runtime.