Intercepting UIButton Touch Events
I was recently building an iPhone app that required a UIButton be held down and then released after a certain period of time had elapsed. The problem I encountered was that testing for touchesBegan didn't work for buttons. I'm not talking about UIControlEvents. I didn't need to know that button had been tapped or it's current state. I needed to know when the button was being pressed and when it was released. The solution was to simply create a UIButton subclass and pass it's touches up the responder chain.
MyButton.h -
[code lang="cpp"]
@interface MyButton : UIButton {
}
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
@end
[/code]
MyButton.m -
[code lang="cpp"]
#import "BrakeButton.h"
@implementation BrakeButton
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.nextResponder touchesBegan:touches withEvent:event]; // This is where the touch is passed on
}
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.nextResponder touchesEnded:touches withEvent:event]; // This is where the touch is passed on
}
@end
[/code]
Then in your view controller be sure to import your new class:
[code lang="cpp"]
#import "MyButton.h"
[/code]
Then you simply implement the touchesBegan and touchesEnded methods.
[code lang="cpp"]
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"Button Touches began");
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"Button Touches ended");
}
[/code]
So what is happening here? The main point to understand is that UIButtons are in actuality just UIViews. So they inherit from UIViews giving them the ability to access UIView-like functionality. (touchesBegan, touchesEnded, etc...) I've seen many folks banging their heads against the wall trying to figure out how to capture / intercept button touches so I apparently it's a pretty common problem. Let me know if you find this helpful.