You know how Mario just keeps running to the right when you press and hold the right-button on the D-Pad? In the same manner, I want my UIButton to continuously fire its action for the duration that it is held down. Is this possible for a UIButton? If not, is this possible to do with a UIImageView by overriding a touch handling method in a certain way? Actually, before trying to do get this done with UIButton I had some UIImageViews (Arranged to function as a D-Pad) that were checked by touch handling methods but things started to get messy so I thought this could be done easier with UIButton and thus switched over. Anybody who knows how to get recognition of a continuous, stationary (not-moved) down-touch, please share.
views:
3350answers:
2
+6
A:
Don't use a button, use multi-touch and NSTimer:
Make a view-local NSTimer object inside your interface, then use it to start/cancel the timer
-(void)movePlayer:(id)sender {
<Code to move player>
}
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
timer = [NSTimer schduleTimerWithTimeInterval:0.3 target:self selector:@selector(movePlayer:) repeats:YES userInfo:nil];
}
-(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
if (timer != nil)
[timer invalidate];
timer = nil;
}
-(void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
if (timer != nil) {
[timer invaidate];
timer = nil;
}
}
This way, you can repeat the event at a predefined interval, and not have to rely on a button, and get the repeat behaviour you're looking for. Note the touchesMoved trigger - if they move their finger, this cancels the timer, and the player stops moving.
Chaos
2009-05-24 05:08:16
You have 2 touchesBegan, I believe the 2nd should be touchesMoved.
freespace
2009-05-24 05:21:28
Great, though could you correct the duplicate touchesBegan trigger to your intended touchesMoved so nobody gets confused.
RexOnRoids
2009-05-24 05:38:02
+10
A:
You can also do similar to what is shown in the previous answer and still use a UIButton.
Just have the timer started on the "Touch Down" and have the timer stopped on either "Touch Up Inside" or "Touch Up Outside".
Personally, I like using UIButtons because they offer some built in visual enhancements you don't have to code on your own.
Brian Stormont
2009-06-15 18:01:25