func addSwipe() { self.isUserInteractionEnabled = true let directions: [UISwipeGestureRecognizerDirection] = [.right, .left] for direction in directions { let gesture = UISwipeGestureRecognizer(target: self, action: #selector(ViewCardContai
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:
+----------------+ | | | +--------+ | | V1 | V2 | | +-----------------
我在V2中注册了UISwipeGestureRecognizer但是如果从V1开始通过V2启动滑动手势,则在V2中将无法识别滑动手势.
反正有没有让它工作?提前致谢!
编辑:我为你做了一个工作示例项目.您可以从红色方块(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应用程序,你会发现从滚动视图中向上移动手指后,你无法按下导航栏中的按钮.
如果您希望触摸识别器在V1和V2中有效:
>在V1和EX的父视图中添加手势识别器. V2
>检测触摸是否在V2的矩形内(使用touch.locationInView:V2)
>如果为true,请运行预期的功能
如果这是一个viewcontroller,你需要将识别器添加到self.view(从你的例子中不清楚识别器添加到哪个视图,因为没有关于你的func所在的类的上下文)
您可能需要禁用V1和V2上的用户交互,如果它正在吃掉触摸并在父视图上保持启用状态.