Search code examples
iossubclasscode-reuseobjective-c-category

Add rounded corners to all UIImageViews


I would like to add some rounded corners to all of the UIImageViews in my project. I have already got the code working, but am having to apply it to every image; should I subclass UIImageView to add this? If so, can someone give me some pointers as to how to do this?

Here is the code

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *mainpath = [[NSBundle mainBundle] bundlePath];
    welcomeImageView.image = [UIImage imageWithContentsOfFile:[mainpath stringByAppendingString:@"/test.png"]];
    welcomeImageView.layer.cornerRadius = 9.0;
    welcomeImageView.layer.masksToBounds = YES;
    welcomeImageView.layer.borderColor = [UIColor blackColor].CGColor;
    welcomeImageView.layer.borderWidth = 3.0;
    CGRect frame = welcomeImageView.frame;
    frame.size.width = 100;
    frame.size.height = 100;
    welcomeImageView.frame = frame;
}

Solution

  • You could use a category for UIImage which is an alternate way to subclass a Class and sometimes easier for just small changes.

    e.g add a method that returns a UIImage with the rounded corner attributes set.

    +(UIImage *)imageWithContentsOfFile:(NSString *)file cornerRadius:(NSInteger)... 
    

    more info on Objective-c categories can be found http://macdevelopertips.com/objective-c/objective-c-categories.html