2017-10-14 86 views
4
func addSwipe() { 
    self.isUserInteractionEnabled = true 
    let directions: [UISwipeGestureRecognizerDirection] = [.right, .left] 
    for direction in directions { 
     let gesture = UISwipeGestureRecognizer(target: self, action: #selector(ViewCardContainer.handleSwipe(sender:))) 
     gesture.direction = direction 
     self.addGestureRecognizer(gesture) 
    } 
} 

@objc func handleSwipe(sender: UISwipeGestureRecognizer) { 
    print(sender.direction) 
} 

我的UIViews轻扫手势:UISwipeGestureRecognizer不承认视野之外发起

+----------------+ 
|    | 
|  +--------+ | 
| V1 | V2 | | 
+----------------- 

我注册了UISwipeGestureRecognizer在V2但如果滑动手势从V1开始通过V2去,滑动手势赢在V2中不会被识别。

有没有办法让它工作?提前致谢!

+1

这是因为您的轻扫手势已注册为V1而非V2。您可以尝试检测从V1启动的手势的触摸位置是否低于V2并调用一些更改 – Woof

回答

7

编辑:我为你做了一个工作示例项目。您可以从红色方块(v1)滑动到蓝色方块(v2),并在日志中看到检测到滑动。

https://github.com/QuantumProductions/so_46781856

import UIKit 

class ViewController: UIViewController { 
    var view2: UIView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     view.backgroundColor = UIColor.black 

     let view1 = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) 
     view1.backgroundColor = UIColor.red 
     view.addSubview(view1) 

     view2 = UIView(frame: CGRect(x: 100, y: 0, width: 100, height: 100)) 
     view2.backgroundColor = UIColor.blue 
     view.addSubview(view2) 

     let swipeRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(swipeDetected(_:))) 
     swipeRecognizer.direction = .right 
     view.addGestureRecognizer(swipeRecognizer) 

    } 

    func swipeDetected(_ sender: UIGestureRecognizer) { 
     let location = sender.location(ofTouch: 0, in: view2) 
     print("Location in view2") 
     print(location) 
     print("You swiped right") 
    } 
} 

原来的答案:

这是故意的。轻扫检测是基于视图的基础视图。尝试一下Apple联系人等Apple应用程序,然后在滚动视图中移动手指后,您将看到无法按导航栏中的按钮。

如果你想你的触摸识别为有效的V1和V2:

  • 添加手势识别两个V1的父视图& V2
  • 检测是否触摸是V2的矩形内(使用touch.locationInView:V2)
  • 如果为真,运行预期功能

如果这是一个视图控制器,你要识别器添加到self.view(从您的示例中不清楚哪个视图添加了识别器,因为没有关于您的func所在的级别的上下文)

您可能需要在V1和V2上禁用用户交互,吃东西,并把它放在父视图上启用。