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中识别滑动手势。
有没有让它发挥作用?提前谢谢!
答案 0 :(得分: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应用程序,你会发现从滚动视图中向上移动手指后,你无法按下导航栏中的按钮。
如果您希望触摸识别器在V1和V2中有效:
如果这是一个viewcontroller,你需要将识别器添加到self.view
(从你的例子中不清楚识别器添加到哪个视图,因为没有关于你的{的哪个类的上下文{1}} s in)
您可能需要禁用V1和V2上的用户互动,如果它正在吃掉触摸并在父视图上保持启用状态。