【问题标题】:Gesture recognizer callback over multiple views多个视图上的手势识别器回调
【发布时间】:2018-08-25 00:21:35
【问题描述】:
我有一个自定义 UIView,它由 9 个大小相同的子视图组成。它本质上看起来像一个井字游戏。
我在这个自定义视图中添加了一个 UIPanGestureRecognizer。每次用户平移其中一个子视图时,我都想采取行动。例如,用户可以用一个手势平移前 3 个(9 个)子视图,在这种情况下,我想要执行 3 个操作。
我可以尝试做一些花哨的数学运算并计算出每个子视图的框架,然后计算出手势何时从一个子视图跨越到另一个子视图。但是,我觉得应该有一种更优雅的方式来在手势触摸新 UIView 时获取回调。有这样的功能吗?
【问题讨论】:
标签:
ios
uipangesturerecognizer
【解决方案1】:
通过使用hitTest,我能够找到一种更优雅的方式,它在启用用户交互的情况下返回最低的子视图。我这样定义了平移手势识别器的回调:
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
}
}
【解决方案2】:
尝试使用堆栈视图对具有相同手势的视图进行分组,并使用
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(stackViewTapped))
myStackView.addGestureRecognizer(tapGesture)
如果需要实现不同的方法,只需添加另一个堆栈视图。