Search code examples
iostouchesmoved

touchesMoved handle first touch event iOS


I'm using this method to move my objects in view:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event

In this method I wrote next:

NSLog(@"event: %@", event);

and get this result:

event: <UITouchesEvent: 0x310d00> timestamp: 5277.16 touches: {(
    <UITouch: 0x3f1110> phase: Moved tap count: 1 window: <UIWindow: 0x3117d0; frame = (0 0; 768 1024); layer = <UIWindowLayer: 0x30cb20>> view: <UIView: 0x330520; frame = (0 0; 768 1024); transform = [0, -1, 1, 0, 0, 0]; autoresize = W+H; layer = <CALayer: 0x330550>> location in window: {279, 677} previous location in window: {305, 694} location in view: {347, 279} previous location in view: {330, 305},
    <UITouch: 0x4a1a710> phase: Stationary tap count: 1 window: <UIWindow: 0x3117d0; frame = (0 0; 768 1024); layer = <UIWindowLayer: 0x30cb20>> view: (null) location in window: {412, 89} previous location in window: {413, 89} location in view: {412, 89} previous location in view: {413, 89}
)}

In this log I can see all my touches (for now this is two touches).

My questions is how to get for touch?

This needs to move my objects.

Now I'm using this:

UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];

But when I move my object I get all values of touches. How to handle just first touch?

Thanks a lot!


Solution

  • There's nothing wrong with the way you do it, but if you'd really like to know, how to get the very first object, here it goes.

    Parameter touches is of NSSet type. If you take a look at NSSet Class Reference you can also find a method - (NSArray *)allObjects.

    So you could retrieve first touch by:

    UITouch *touch = (UITouch *)[[[event allTouches] allObjects] objectAtIndex: 0];
    

    Also take a look at UIEvent Class Reference. There you'll find that allTouches is not the only method. Class also knows how to return:

    - (NSSet *)touchesForGestureRecognizer:(UIGestureRecognizer *)gesture
    
    - (NSSet *)touchesForView:(UIView *)view
    
    - (NSSet *)touchesForWindow:(UIWindow *)window
    

    All of this methods return a NSSet. Which you can convert to NSArray using NSSet's allObjects method.