How to detect swiping left / right on the iPhone?

后端 未结 3 765
梦毁少年i
梦毁少年i 2021-02-04 07:50

Is there any easy way to detect these kinds of gestures for iPhone? I can use touchesBegan, touchesMoved, touchesEnded. But how can I implement the gestures? thz u.

相关标签:
3条回答
  • 2021-02-04 08:29

    If you're willing to target iPhone OS 3.2 or later (all iPads or updated iPhones), use the UISwipeGestureRecognizer object. It will do this trivially, which is wickedly cool.

    0 讨论(0)
  • 2021-02-04 08:31

    You are on the right track. In touchesBegan you should store the position where the user first touches the screen.

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
        UITouch *touch = [touches anyObject];
        self.startPosition = [touch locationInView:self];
    }
    

    Similar code in touchesEnded gives you the final position. By comparing the two positions you can determine the direction of movement. If the x-coordinate has moved beyond a certain tolerance you have a left or right swipe.

    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    
        UITouch *touch = [touches anyObject]; 
        CGPoint endPosition = [touch locationInView:self];
    
        if (startPosition.x < endPosition.x) {
            // Right swipe
        } else {
            // Left swipe
        }
    }
    

    You do not need touchesMoved unless you want to detect and track a swipe while the user is still touching the screen. It may also be worth testing that the user has moved a minimal distance before deciding they have performed a swipe.

    0 讨论(0)
  • 2021-02-04 08:38

    You will using UISwipeGestureRecognizer Object to detect the Touch and direction of Swipe In

    UIView or anywhere in iphone sdk.

     UISwipeGestureRecognizer *rightRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightSwipeHandle:)];
    rightRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
    [rightRecognizer setNumberOfTouchesRequired:1];
    
    //add the your gestureRecognizer , where to detect the touch..
    [view1 addGestureRecognizer:rightRecognizer];
    [rightRecognizer release];
    
    UISwipeGestureRecognizer *leftRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(leftSwipeHandle:)];
    leftRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
    [leftRecognizer setNumberOfTouchesRequired:1];
    
    [view1 addGestureRecognizer:leftRecognizer];
    [leftRecognizer release];
    
     - (void)rightSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
     {
         NSLog(@"rightSwipeHandle");
     }
    
     - (void)leftSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer 
     {
    NSLog(@"leftSwipeHandle");
     }
    

    I think this the Better solution for your problem

    0 讨论(0)
提交回复
热议问题