Search code examples
iosautolayoutrounded-corners

Rounded corners of UIView with autolayout cropping the view


I am creating IOS app with autolayout enable. In my app for views there are rounded corners (top corners only). I am using the following function:

- (void)setMaskTo:(UIView*)view byRoundingCorners:(UIRectCorner)corners
{
    UIBezierPath *rounded = [UIBezierPath bezierPathWithRoundedRect:view.bounds
                                                  byRoundingCorners:corners
                                                        cornerRadii:CGSizeMake(5.0, 5.0)];
    CAShapeLayer *shape = [[CAShapeLayer alloc] init];
    [shape setPath:rounded.CGPath];
    view.layer.mask = shape;
}

and calling this function in viewDidAppear like:

-(void)viewDidAppear:(BOOL)animated {

    [self setMaskTo:contentView byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight]; 
}

This is working fine, but the issue is when app is in landscape mode and when I am navigating from one view to another, it is cropping the view like Portrait view. Please let me know is there any issue with this approach?


Solution

  • Autolayout won't recalculate your mask, so you will have to set the mask each time your layout changes. Move setMaskTo:byRoundingCorners: from viewDidAppear: to viewDidLayoutSubviews:

    - (void)viewDidLayoutSubviews{
        [super viewDidLayoutSubviews];
        [self setMaskTo:contentView byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight];
    }