You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

报错‘UIGestureRecognizer无numberOfTapsRequired成员’原因排查

Fixing the "UIGestureRecognizer has no member 'numberOfTapsRequired'" Error

Hey there! Let's break down why that double-tap gesture code is throwing an error for you.

What's Causing the Issue?

The problem comes down to type mismatch. The numberOfTapsRequired property is unique to UITapGestureRecognizer—the subclass of UIGestureRecognizer designed specifically for tap interactions. If you declare your gesture variable as the parent UIGestureRecognizer type instead of the tap-specific subclass, the compiler won't recognize this property, hence the error you're seeing.

How to Fix It in Your addDoubleTap Function

Here's the corrected way to set up your double-tap gesture in your MapViewController:

func addDoubleTap() {
    // 1. Initialize a UITapGestureRecognizer (not the generic parent class)
    let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(_:)))
    
    // 2. Now you can safely access numberOfTapsRequired
    doubleTapGesture.numberOfTapsRequired = 2
    
    // 3. Set delegate if you need to handle gesture conflicts (like with the map's default zoom/pan)
    doubleTapGesture.delegate = self
    
    // 4. Add the gesture to your map view
    mapView.addGestureRecognizer(doubleTapGesture)
}

// Don't forget the handler method (must be @objc for selector compatibility)
@objc private func handleDoubleTap(_ gesture: UITapGestureRecognizer) {
    // Add your double-tap logic here—e.g., zoom the map or drop an annotation
    let tapPoint = gesture.location(in: mapView)
    let coordinate = mapView.convert(tapPoint, toCoordinateFrom: mapView)
    print("Double-tapped at coordinate: \(coordinate)")
}

If You're Working with Existing Gesture Recognizers

If you're modifying a gesture already attached to your map view (instead of creating a new one), you'll need to cast it to UITapGestureRecognizer first:

// Example: Adjusting an existing tap gesture
if let existingTapGesture = mapView.gestureRecognizers?.first(where: { $0 is UITapGestureRecognizer }) as? UITapGestureRecognizer {
    existingTapGesture.numberOfTapsRequired = 2
}

Quick Tips to Avoid This in the Future

  • Always use UITapGestureRecognizer when working with tap-based gestures (single or double) to access tap-specific properties like numberOfTapsRequired and numberOfTouchesRequired.
  • Ensure your gesture handler method is marked with @objc—selectors rely on Objective-C compatibility to work.
  • If you run into conflicts between your custom gesture and the map's default gestures, use UIGestureRecognizerDelegate methods like gestureRecognizer(_:shouldRecognizeSimultaneouslyWith:) to resolve them.

内容的提问来源于stack exchange,提问作者Vinny Twice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:13:18