Update for Swift:
The below answer was correct that the time it was written for simple use cases. Things have changed a lot since then so heres an updated answer for swift.
You can create a UIView extension, to add methods to round all corners, or round specific corners. Adding @IBInspectable
to the first property means it can be used in interface builder without requiring code
The second function is more complicated and can't be used as an @IBInspectable
directly. It will need to be called inside the viewDidLayoutSubviews
of the parent to ensure the mask doesn't cut off content as AutoLayout grows / shrinks the content.
extension UIView {
@IBInspectable public var cornerRadius: CGFloat {
set {
layer.cornerRadius = newValue
}
get {
return layer.cornerRadius
}
}
public func roundCorners(corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
}
}
Once added to your project you can simply do:
myView.cornerRadius = 4
or
myView.roundCorners(corners: [.topLeft, .topRight], radius: 4)
Very old Objective-c answer:
If you import QuartzCore framework:
#import <QuartzCore/QuartzCore.h>
and add it to your project, you can use the below:
UIView *temp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
temp.layer.cornerRadius = 5;