我想覆盖双击 mapView 的默认行为。
在我的 swift
应用程序中,我在静态单元格中有一个 mapView
,所以在方法 cellForRowAt
中,我决定添加一个 UITapGestureRecognizer
。我是这样做的:
func tableView(_ myTable: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath as NSIndexPath).row == 0 {
let cell = myTable.dequeueReusableCell(withIdentifier: "cellStatic") as! MyTableDetailsCell
cell.mapView.isScrollEnabled = false //this works
//this does not:
let tap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped))
tap.numberOfTapsRequired = 2
cell.mapView.addGestureRecognizer(tap)
...
然后我有一个简单的函数:
func doubleTapped() {
print("map tapped twice")
}
但是当我点击两次 map 时 - 它放大并且控制台日志中没有打印 - 所以我的代码不起作用。我错过了什么?
最佳答案
您必须强制您自己的双击手势识别器禁用 mapView
的标准双击手势识别器。
这可以使用委托(delegate)方法来完成:
使用 UIGestureRecognizerDelegate
将您的 View Controller 声明为手势识别器的委托(delegate)
为您自己的双击手势识别器定义一个属性:
var myDoubleTapGestureRecognizer: UITapGestureRecognizer?
设置双击手势识别器,例如在 viewDidLoad
中:
myDoubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(doubleTapped))
myDoubleTapGestureRecognizer!.numberOfTapsRequired = 2
myDoubleTapGestureRecognizer!.delegate = self
mapView.addGestureRecognizer(myDoubleTapGestureRecognizer!)
注意,委托(delegate)是在这里设置的。
实现以下委托(delegate)方法:
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if ((gestureRecognizer == myDoubleTapGestureRecognizer) && (otherGestureRecognizer is UITapGestureRecognizer)) {
let otherTapGestureRecognizer = otherGestureRecognizer as! UITapGestureRecognizer
return otherTapGestureRecognizer.numberOfTapsRequired == 2
}
return true
}
因此,当您双击 mapView
时,如果另一个手势识别器是 mapView 的内置双击识别器,则此委托(delegate)方法返回
。这意味着内置的双击识别器只能在您自己的双击识别器无法识别双击时触发,但它不会。true
我测试了一下: map 不再缩放,方法 doubleTapped
被调用。
关于ios - 为什么我的 UITapGestureRecognizer 在我将它附加到 UITableViewCell 中的元素时不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40114326/