Prajeet Shrestha Prajeet Shrestha - 5 months ago 49
Objective-C Question

How to reduce code redundancy while subclassing views?

I have a requirement where I need to alter UIComponents like UIButton, UIView and UITextField. What I need to do is just to make change the radius of border to round rather than sharp rectangle which is default.

The way I have done this is to subclass UIView to UIViewRoundCorner, UIButton to UIButtonRoundCorner, UITextField to UITextFieldRoundCorner and inside each subclass I have overridden the drawRect Method with this:

- (void)drawRect:(CGRect)rect {
// Drawing code
CALayer *layer = [self layer];
[layer setMasksToBounds:YES];
[layer setCornerRadius:3.0f];
[layer setBorderWidth:1.0f];

The code is redundant and I am trying to figure out how to remove this redundancy. Since all these element is being inherited from UIView, is it possible somehow to subclass UIView and implement in all the other views?

protocol RoundedCorner {
    func makeCornerRadius(radius:CGFloat)

extension RoundedCorner where Self:UIView{
    func makeCornerRadius(radius:CGFloat){
        self.layer.cornerRadius = radius

class CustomButton: UIButton, RoundedCorner {

    override func drawRect(rect: CGRect) {

you can create a protocol and extend that protocol for default implementation. and then for every custom view for which you want corner radius, just implement that protocol. This way you can minimise your code redundancy.