Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclassing UIButton to handle clicks [closed]

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?)

like image 340
Andy Hin Avatar asked Aug 28 '12 16:08

Andy Hin


1 Answers

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.

like image 190
kubi Avatar answered Oct 24 '22 03:10

kubi