Giving UIView rounded corners Giving UIView rounded corners ios ios

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.


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.

Using Interface builder to set the corner radius


Now you can use a swift category in UIView (code bellow the picture) in with @IBInspectable to show the result at the storyboard (If you are using the category, use only cornerRadius and not layer.cornerRadius as a key path.

extension UIView {    @IBInspectable var cornerRadius: CGFloat {        get {            return layer.cornerRadius        }        set {            layer.cornerRadius = newValue            layer.masksToBounds = newValue > 0        }    }}

enter image description here