Corners as round as Kim's

What? Nothing...

The old, ugly and down right bad way

// Objective-C

UIView *roundedView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
[roundedView setClipsToBounds:YES];
[roundedView.layer setCornerRadius:30];
[self.view addSubview:roundedView];
// Swift

let roundedView = UIView(frame: CGRect(x: 0, y: 0, width: 60, height: 60))
roundedView.clipsToBounds = true
roundedView.layer.cornerRadius = 30
view.addSubview(roundedView)

The good, better and only way

// Objective-C

@interface UIView (Rounded)
// (UIView *) could also be (void), I've not written Objective-C for some time
-(UIView *) roundCorners:(UIRectCorner)corners radius:(CGFloat)radius;
@end

@implementation UIView (Rounded)
-(UIView *) roundCorners:(UIRectCorner)corners radius:(CGFloat)radius {
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds 
    byRoundingCorners:corners cornerRadii:CGSizeMake(radius, radius)];
    
    CAShapeLayer *mask = [[CAShapeLayer alloc] init];
    [mask setPath:path.CGPath];
    [self.layer setMask:mask];
}
@end

// How to call this method:
/*
    [myView roundCorners:UIRectCornerAllCorners radius:30];
*/
// Swift

extension UIView {
    func round(corners: UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: self.bounds, 
        byRoundingCorners: corners, cornerRadii:CGSize(width: radius, height: radius))
        
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        layer.mask = mask
    }
}

// How to call this method:
/*
    myView.round(corners: .all, radius: 30)
*/

This is very easy and the result is subtle but worth the extra bit of code

Last updated