How to add a vertical swipe gesture to iPhone app

2019-02-09 03:07发布

I'd like to add a gesture to my app so when the user swipes vertically it triggers a method to do something. The swipe can be up or down. I've never done anything with gestures so this is my first use of a gesture other than what is included in a UITableView for deleting rows.

The other problem is that most of my screens are UITableViews so the user could be simply scrolling the UITableView. So I am wondering if I could use a two finger swipe (vertical) to detect the gesture to run the code vs. a single finger swipe to scroll the UITableView?

Thank you in advance.

Neal

2条回答
smile是对你的礼貌
2楼-- · 2019-02-09 03:39

This goes in ApplicationDidLaunch:

UISwipeGestureRecognizer *swipeGesture = [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipedScreen:)] autorelease];
swipeGesture.numberOfTouchesRequired = 2;
    swipeGesture.direction = (UISwipeGestureRecognizerDirectionUp|UISwipeGestureRecognizerDirectionDown);

[window addGestureRecognizer:swipeGesture];

then implement

- (void) swipedScreen:(UISwipeGestureRecognizer*)swipeGesture {
   // do stuff
}

Use the documentation for UIGestureRecognizer and UISwipeGestureRecognizer.

Also if you wish to detect the direction of the swipe you will have to setup two separate gesture recognizers. You can not get the direction of a swipe from a swipe gesture recognizer, only the directions it is registered to recognize.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-02-09 03:41

In swift 4.0, that goes on the method didFinishLaunchingWithOptions of the AppDelegate:

let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(self.swipedScreen(swipeGesture:)))
swipeGesture.numberOfTouchesRequired = 2
swipeGesture.direction = [UISwipeGestureRecognizerDirection.up,  UISwipeGestureRecognizerDirection.down]
window?.addGestureRecognizer(swipeGesture)

And the action:

@objc func swipedScreen(swipeGesture: UISwipeGestureRecognizer){
    Swift.print("hy")
}
查看更多
登录 后发表回答