Viktorianec Viktorianec - 25 days ago 13
iOS Question

How get textfield with some corners rounded?

This is textfield which I get right now

I use next code:

- (void)setMaskByRoundingCorners:(UIRectCorner)corners withCornerRadius:(float)radius
{
UIBezierPath* rounded = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(radius, radius)];

CAShapeLayer* shape = [[CAShapeLayer alloc] init];
[shape setPath:rounded.CGPath];
shape.frame = self.bounds;
self.layer.mask = shape;
}


But now I see this strange effect.

I call it from viewcontroller, after didlayoutsubviews. I do that for main thread updating.

- (void)viewDidLayoutSubviews
{
[self initUIfeatures];
}

- (void)initUIfeatures
{
[authTextField setMaskByRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight|UIRectCornerBottomLeft) withCornerRadius:8.0f];
}


The issue is rounded corners getting cutoff.

Answer

Add these functions,

-(void)roundCorners:(UIRectCorner)corners radius:(CGFloat)radius
{
    CGRect bounds = _IBtxtField.bounds;
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bounds
                                                   byRoundingCorners:corners
                                                         cornerRadii:CGSizeMake(radius, radius)];

    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = bounds;
    maskLayer.path = maskPath.CGPath;

    _IBtxtField.layer.mask = maskLayer;

    CAShapeLayer*   frameLayer = [CAShapeLayer layer];
    frameLayer.frame = bounds;
    frameLayer.path = maskPath.CGPath;
    frameLayer.strokeColor = [UIColor blackColor].CGColor;
    frameLayer.fillColor = nil;

    [_IBtxtField.layer addSublayer:frameLayer];
}

-(void)roundCornersRadius:(CGFloat)radius
{
    [self roundCorners:(UIRectCornerTopLeft|UIRectCornerTopRight | UIRectCornerBottomLeft) radius:radius];
}

Use like this,

[self roundCornersRadius:10];

Ref

SourceCode

Comments