多个视图上的手势识别器回调

Gesture recognizer callback over multiple views

我有一个自定义 UIView,它包含 9 个大小相同的子视图。它本质上看起来像一个井字棋盘。

我已将 UIPanGestureRecognizer 添加到此自定义视图。每次用户平移其中一个子视图时,我都想采取行动。例如,用户可以用一个手势平移前 3 个(9 个中的)子视图,在这种情况下我想采取 3 个动作。

我可以尝试做一些花哨的数学运算并计算出每个子视图的框架,然后计算出手势何时从一个子视图交叉到另一个子视图。但是,我觉得应该有一种更优雅的方式来在手势触摸新的 UIView 时获得回调。是否存在这样的功能?

我能够通过使用 hitTest 找到更优雅的方式,returns 启用用户交互的最低子视图。我这样定义了平移手势识别器的回调:

var panSelected = Set<UILabel>()
@objc func handlePan(recognizer: UIPanGestureRecognizer) {
    let view = recognizer.view
    let loc = recognizer.location(in: view)
    if let gridLabel = view?.hitTest(loc, with: nil) as? UILabel {
        if !panSelected.contains(gridLabel) {
            // my code here
        }
    }

尝试使用堆栈视图对具有相同手势的视图进行分组,并使用

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(stackViewTapped))
myStackView.addGestureRecognizer(tapGesture)

如果需要实现不同的方法,只需添加另一个堆栈视图即可。