Method swizzling is a very good option to achieve this.
Create a UIImageView category class and swizzle initWithCoder: method
#import "UIImageView+MethodSwizzling.h"
#import <objc/runtime.h>
@implementation UIImageView (MethodSwizzling)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = @selector(initWithCoder:);
SEL swizzledSelector = @selector(xxx_initWithCoder:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
// When swizzling a class method, use the following:
// Class class = object_getClass((id)self);
// ...
// Method originalMethod = class_getClassMethod(class, originalSelector);
// Method swizzledMethod = class_getClassMethod(class, swizzledSelector);
BOOL didAddMethod =
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
}
else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
#pragma mark - Method Swizzling
- (id)xxx_initWithCoder:(NSCoder*)aDecoder {
[self xxx_initWithCoder:aDecoder];
self.layer.cornerRadius = self.frame.size.width / 2;
self.layer.masksToBounds = YES;
NSLog(@"xxx_initWithCoder: %@", self);
return self;
}
You don't have to create subclass of UIImageView and do not need to change your object's class everywhere in XIB/Storybord.
Click here to know about method swizzling.