views:

511

answers:

2

How can you tell when a button is being pressed? Specifically, how can you do something while a button is down?

+2  A: 

While the screen is touched, there will be touch events. There are also touch up and touch down events.

  • (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { NSLog(@"touchesBegan"); }

  • (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { NSLog(@"touchesMoved"); }

  • (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { NSLog(@"touchesEnded"); }

Then just register your controller as the touchController.

Also check out Apple's GLPaint example: https://developer.apple.com/iphone/library/samplecode/GLPaint/

John
That is a lot of work when you can just attach an action to "TouchDownInside" for any UIControl.
Kendall Helmstetter Gelner
+2  A: 

You can also do it by creating an IBAction and connecting it IB. Interface builder for iPhone can actually demux different types of events. If you ctrl-click a UIButton in your UI, and release the mouse button instead of dragging a connection you will see an inspector that shows a bunch of different actions you can wire up. When you just drag it defaults to wiring up "Touch Up Inside", but if you want you can wire up "Touch Down" or "Touch Down Repeat" and that action will be cause the appropriate selector to be called.

If you are doing complicated stuff with your own gestures then using the touchController based stuff will definitely be a better approach, but for simple things just using the built in nib based actions may be simpler.

Louis Gerbarg