Last Updated: December 30, 2020
·
11.61K
· jvashishtha

UIView category for rounding just the corners which you want, not all like CALayer cornerRadius.

Often times, you just want to round left corners or bottom corners, not all of them. CALayer has an attribute called cornerRadius, but that rounds all the corners. What if you want to round just the corners you want? This category helps you do that.

UIView+RoudedCorners.h

================
#import <UIKit/UIKit.h>

@interface UIView (RoundedCorners)

-(void)setRoundedCorners:(UIRectCorner)corners radius:(CGFloat)radius;

@end

UIView+RoundedCorners.m

================
#import "UIView+RoundedCorners.h"
#import <QuartzCore/QuartzCore.h>

@implementation UIView (RoundedCorners)

-(void)setRoundedCorners:(UIRectCorner)corners radius:(CGFloat)radius {
    CGRect rect = self.bounds;

    // Create the path 
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corners cornerRadii:CGSizeMake(radius, radius)];

    // Create the shape layer and set its path
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = rect;
    maskLayer.path = maskPath.CGPath;

    // Set the newly created shape layer as the mask for the view's layer
    self.layer.mask = maskLayer;
}

@end

Usage

================
Import the category first:

#import UIView+RoundedCorners.h

Use the following to round all corners:

[myView setRoundedCorners:UIRectCornerAllCorners radius:10.0];

For Top Left and Top Right:

[myView setRoundedCorners:UIRectCornerTopLeft|UIRectCornerTopRight radius:10.0];

Here I have used the inbuilt enum UIRectCorner for specifying the rounded corners. So its much simpler to implement.

2 Responses
Add your response

honestly I never needed, but it's brilliant nonetheless.

over 1 year ago ·

Works like a charm, thanks.

over 1 year ago ·