How to detect swiping left / right on the iPhone?

后端 未结 3 763
梦毁少年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: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.

提交回复
热议问题