Skip to content


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 -

@interface MyButton : UIButton {

}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;

@end

MyButton.m -


#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

Then in your view controller be sure to import your new class:

#import "MyButton.h"

Then you simply implement the touchesBegan and touchesEnded methods.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	NSLog(@"Button Touches began");
 }

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	NSLog(@"Button Touches ended");
}

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.

Posted in Application, Code, cocoa touch, iphone development, objective-c.

Tagged with , , , , .

blog comments powered by Disqus

Twitter Feed