Jacob has a good point that category methods act differently than subclass methods. Apple strongly suggests that you only provide category methods that are entirely new, because there are multiple things that can go wrong otherwise - one of those being that defining a category method basically erases all other existing implementations of the same-named method.
Unfortunately for what you're trying to do, UIButton
seems to be specifically designed to avoid subclassing. The only sanctioned way to get an instance of a UIButton
is through the constructor [UIButton buttonWithType:]
. The problem with a subclass like Jacob suggests (like this):
@implementation MyCustomButton
+ (id)buttonWithType:(UIButtonType)buttonType {
return [super buttonWithType:buttonType]; //super here refers to UIButton
}
@end
is that the type returned by [MyCustomButton buttonWithType:]
will still be a UIButton
, not MyCustomButton
. Because Apple hasn't provided any UIButton
init methods, there's not really a way for a subclass to instantiate itself and be properly initialized as a UIButton
.
If you want some customized behavior, you can create a custom UIView
subclass that always contains a button as a subview, so that you can take advantage of some of UIButton
's functionality.
Something like this:
@interface MyButton : UIView {}
- (void)buttonTapped;
@end
@implementation MyButton
-(id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = self.bounds;
[button addTarget:self action:@selector(buttonTapped)
forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
}
return self;
}
- (void)buttonTapped {
// Respond to a button tap.
}
@end
If you want the button to do different things depending on more complex user interactions, you can make more calls to [UIButton addTarget:action:forControlEvents:]
for different control events.
Reference: Apple's UIButton class reference