Search code examples
iosuiviewautosize

Round corners for autosizing UIView


Is it possible to make rounded corners (topLeft and topRight) to autosizing uiview? Here is my code:

SFDetailViewController.h

@interface SFDetailViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, PopoverViewListDelegate>
{
  ...

  UIView *header;
}
@property (nonatomic, retain) IBOutlet UIView *header;

@end

SFDetailViewController.m

#import "SFDetailViewController.h"
#import <QuartzCore/QuartzCore.h>

@interface SFDetailViewController ()
@end


@implementation SFDetailViewController
@syntesyze header;

-(void) viewDidLoad
{
    ....
    [self setCornerRadiusToHeader:header];
 }



-(void) setCornerRadiusToHeader:(UIView *)headerView
{    
    CGRect bounds = headerView.layer.bounds;
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bounds 
                                               byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight)
                                                     cornerRadii:CGSizeMake(8.0, 8.0)];

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

    [headerView.layer addSublayer:maskLayer];
    headerView.layer.mask = maskLayer; 

}

The view is defined in IB as:

IB

What I get - the topRight corner is straight, because the size of the view is dynamic.

result


Solution

  • You need to set your UIView's contentMode property to something like UIViewContentModeRedrew. The content mode controls how the view's content changes when its bounds are changed (like when it is autoresized). By default, it just stretches the view's contents, which is why your corners get stretched.