Querying current number of touches on screen without using events on iPhone
I have an application that starts playing a sound when user touches the uiview and changing to different tones as the u开发者_运维知识库ser slides the finger on the screen. The sound stops when the user lifts the finger.
I am using the touchesBegan, Moved and Ended Events for this.
My problem is touches Ended (and/or cancelled) is sometimes not fired properly and the sound keeps playing even after the finger is lifted from screen.
So as a workaround I would like to implement a timer that would check for the number of touches on the screen and if it is zero it will check and stop the audioplayer if playing.
I have been searching for some code that could get me the number of touches like
UITouch *touches=[self getAllTouchesonScreen];
or something :)
NSSet *allTouches = [event allTouches];
for(GLuint index = 0; index < [allTouches count]; ++index)
{
UITouch *touch = [[allTouches allObjects] objectAtIndex:index];
if([touch phase] != UITouchPhaseCancelled)
{
CGPoint touchPoint = [touch locationInView:self];
//do something with touchPoint that has state [touch phase]
}
}
You can use this code in all touch event functions(touchesBegan, touchesEnded, touchesMoved) and you can count touches and know their states.
Touches Ended Event sometimes does not get fired.
I have tried setting break points for touches cancelled and touches ended events and it sometimes doesnt hit.
try the GLPaint sample program from Apple website and try an NSLog in toches ended and do some fast drawings on screen and lift the finger fast, like throwing the finger off screen.
You will know what I mean. My current solution for this involves accelerometer :)
Hint : I use this to find all events : (void)sendEvent:(UIEvent *)event
Don't forget about touchesCanceled. Add this function/method and NSLog it when a touch ends up there I think you'll find some missing touches.
If you're looking for a tap count - tapping in the same place more than once without moving the finger much - you can get it via:
-(void)iPhoneTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint touchPosition = [touch locationInView:self];
lastTouchTime = [touch timestamp];
myTouchCount = [touch tapCount];
But I also do it manually using touchesMoved to see how FAR it moved and canceling the ability to double/triple tap if any of the taps moved too far, and counting taps as long as you're in a valid tap state.
精彩评论