0

I want to add borders and corner radius to my UIButtons,UITextFields, etc

I think I could extend UIControl to add this functionality.

I would need to add some properties and draw in awakeFromNib or 'layoutSubviews'.

If I subclass UIControl, I can't make UIButton use that subclass. If I subclass my UIControl subclass, I need to "recreate" UIButton, UITextField, etc. I could subclass UIButton, UITextField and add this behaviour, but then I would have one subclass for each component to add the same functionality to them, ending with a lot of duplicated code.

I think I can not change/alter UIControl's methods in a category.

Is there a way to add this kind of functionality to UIControl and it's subclasses without reinventing the wheel, or ending up with a lot of duplicated code?

Tiago Veloso
  • 8,513
  • 17
  • 64
  • 85

2 Answers2

1

What HellBoy89 says seems the easiest route to go on. Categories can also override default implementation, which makes things practical here. Here's an example to do what you want and it's automatically applied to all UIControls and their subclasses being instantiated.

@implementation UIControl (Styling)
  - (id) initWithFrame:(CGRect)frame {
     self = [super initWithFrame:frame];
     if (self) {
        [self applyDefaultControlStyle];
     }    
      return self;
  }

  -(id)initWithCoder:(NSCoder *)aDecoder {
      self = [super initWithCoder:aDecoder];
      if (self) {
         [self applyDefaultControlStyle];
      }
      return self;
  }

  -(void)applyDefaultControlStyle {
     [[self layer] setCornerRadius:8];
     [[self layer] setBorderColor: [[UIColor redColor] CGColor]];
     [[self layer] setBorderWidth: 2];
  }
@end
Justin Hammenga
  • 1,091
  • 1
  • 8
  • 14
0

You can use categories to extend UIControl. You will not be able to add properties to UIControl, but you can add methods. Please refer to this question, it may be helpful: Adding a property to all of my UIControls

Community
  • 1
  • 1