ios - 为什么我的 UITapGestureRecognizer 在我将它附加到 UITableViewCell 中的元素时不起作用?

标签 ios swift uitableview mapkit uitapgesturerecognizer

我想覆盖双击 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/

相关文章:

ios - 使用 loadNibNamed 时,为什么我们必须使用 'first' ?我们不想分离源代码的不同实体吗?

ios - 访问 UInavigationcontroller 嵌入式 View Controller ?

ios - 如何从 UIStoryboardPopoverSegue 获取由 UIPopoverController 包装的 View Controller ?

Swift - 无法将用户手势从自定义 UICollectionViewCell 传递到其中的 UITextField

swift - 嵌入式 TableViewController 上未显示导航栏 - Swift

ios - 如何使用复选标记选择所有行作为默认行?

ios - Crossfade 多个 UIViews 没有背景通过 alpha 偷看?

ios - 如何在滚动时使tableView单元格为 "stick"

swift - 将 UIButtons 添加到折线图中的数据点,在 X 轴上绘制日期和时间

ios - 只有当核心数据和 NSFetchedResultsController 满足某些条件时,才在 UITableViewCell 中实现 UIImageView