Receive user input from UISwipeGestureRecognizer and UIScrollView

时间:2015-07-13 21:06:48

标签: ios swift uiscrollview uigesturerecognizer

I am trying to create a UIScrollView that performs an action on scrollViewWillBeginDragging and also recognizes left and right swipes using UISwipeGestureRecognizer. When I use the scrollViewWillBeginDragging function, I get the desired result on a left swipe but my function cannot tell whether I am performing a right or left swipe. If I set detailScrollView.userInteractionEnabled = false, the gestureRecognizer performs correctly but the view no longer scrolls. Here is my code:

override func viewDidLoad() {
    super.viewDidLoad()

    var leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:"))
    var rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:"))

    leftSwipe.direction = .Left
    rightSwipe.direction = .Right

    view.addGestureRecognizer(leftSwipe)
    view.addGestureRecognizer(rightSwipe) }


func gestureRecognizer(UIGestureRecognizer,
    shouldRecognizeSimultaneouslyWithGestureRecognizer:UIGestureRecognizer) -> Bool {
        return true
}

func scrollViewWillBeginDragging(scrollView: UIScrollView) {
    if (counter < buttons.count) {
        serialSelected(buttons[counter])
        counter += 1
    }
}

func handleSwipes(sender:UISwipeGestureRecognizer) {
    if (sender.direction == .Left) {
        println("Swipe Left")
        var labelPosition = CGPointMake(self.contentView.frame.origin.x - 50.0, self.contentView.frame.origin.y);
        contentView.frame = CGRectMake( labelPosition.x , labelPosition.y , self.contentView.frame.size.width, self.contentView.frame.size.height)
    }

    if (sender.direction == .Right) {
        println("Swipe Right")
        var labelPosition = CGPointMake(self.contentView.frame.origin.x + 50.0, self.contentView.frame.origin.y);
        contentView.frame = CGRectMake( labelPosition.x , labelPosition.y , self.contentView.frame.size.width, self.contentView.frame.size.height)
    }
}

1 个答案:

答案 0 :(得分:1)

根据您的源代码,永远不会调用shouldRecognizeSimultaneouslyWithGestureRecognizer:UIGestureRecognizer

// Make yourself a delegate
class yourClass: parentClass, UIGestureRecognizerDelegate

// reference the delegate
leftSwipe.delegate = self
rightSwipe.delegate = self