I am trying to subclass the UIButton to create a "smarter" button that contains logic for handling the click event.
What is the best way to achieve this? Do I simply need to override an onClick method? Or do I need to register an event handler (and if so, where should this be done seeing as there are many ways to init a UIButton?)
I think there are better solutions to this problem than what you've proposed, but to answer your question directly: A subclass of UIButton observes touch events the same way that everyone else observes touch events.
// In your UIButton subclass
- (instancetype)initWithFrame:(CGRect)frame {
self = [super buttonWithType:UIButtonTypeCustom];
if (self) {
[self addTarget:self action:@selector(didTouchButton) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
- (void)didTouchButton {
// do whatever you need to do here
}
Important note: you can't use [UIButton buttonWithType:]
to create your button, you've got to use init
or initWithFrame:
. Even though UIButton has the convenience initializer, initWithFrame:
is still the designated initializer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With