【问题标题】:Swift not firing touchesBegan if swipe如果滑动,Swift 不会触发 touchesBegan
【发布时间】:2015-08-04 02:44:14
【问题描述】:

您好,我有一个 swift 应用程序,每次触摸都开始调用一个函数,但是如果用户正在滑动,我不希望 touchesBegan 被调用。我怎样才能避免这种情况?

开始接触:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
//function call
}

滑动:

var Swipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:"))
    Swipe.direction = .Up
    //Swipe.cancelsTouchesInView = true        did not make a difference
    view.addGestureRecognizer(Swipe)

我也不想做触摸结束,因为这增加了我无法拥有的延迟

【问题讨论】:

    标签: swift touchesbegan


    【解决方案1】:

    使您的 UIViewController 的视图成为一个自定义类并在那里处理这些触摸 - 它们应该按照您尝试的方式接收,但只能在 UIView 类本身中。

    【讨论】:

      【解决方案2】:

      如果您想将滑动与触摸分开,您可以使用 delaysTouchesBegan 方法轻松完成,例如:

              let swipeRight:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedRight:"))
              swipeRight.direction = .Right
              swipeRight.cancelsTouchesInView = true
              swipeRight.delaysTouchesBegan = true
              view.addGestureRecognizer(swipeRight)
      
      
              let swipeLeft:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedLeft:"))
              swipeLeft.direction = .Left
              swipeLeft.cancelsTouchesInView = true
              swipeLeft.delaysTouchesBegan = true
              view.addGestureRecognizer(swipeLeft)
      
      
              let swipeUp:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedUp:"))
              swipeUp.direction = .Up
              swipeUp.cancelsTouchesInView = true
              swipeUp.delaysTouchesBegan = true
              view.addGestureRecognizer(swipeUp)
      
      
              let swipeDown:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedDown:"))
              swipeDown.direction = .Down
              swipeDown.cancelsTouchesInView = true
              swipeDown.delaysTouchesBegan = true
              view.addGestureRecognizer(swipeDown)
      

      在您的 viewDidLoad 或 didMoveToView 中(如果您在 spritekit 场景中)

      并分别制作方法:

      func swipedRight(sender:UISwipeGestureRecognizer){
         print("swiped right")
      }
      
      func swipedLeft(sender:UISwipeGestureRecognizer){
         print("swiped left")
      }
      
      func swipedUp(sender:UISwipeGestureRecognizer){
         print("swiped up")
      }
      
      func swipedDown(sender:UISwipeGestureRecognizer){
         print("swiped down")
      }
      

      然后您可以使用官方委托方法来控制您的触摸,例如:

      override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
      ...// handle your touches..
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-15
        • 2020-12-29
        • 1970-01-01
        • 1970-01-01
        • 2017-03-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多