谷歌地图中的长按

6

帮我解决问题。我正在尝试在Google地图上跟踪长按事件,但我无法做到。这是我的代码示例:

import UIKit
import GoogleMaps

class ViewController: UIViewController {
@IBOutlet var mMap: GMSMapView!

var longPressRecognizer = UILongPressGestureRecognizer()

@IBAction func longPress(_ sender: UILongPressGestureRecognizer) {
    testTextview.text = "You tapped at YES"
}

override func viewDidLoad() {
    super.viewDidLoad()

 longPressRecognizer = UILongPressGestureRecognizer(target: self, 
 action: #selector(self.longPress))
 longPressRecognizer.minimumPressDuration = 0.5
 mMap.addGestureRecognizer(longPressRecognizer)

 mMap.isMyLocationEnabled = true 
 mMap.settings.compassButton = true 
 mMap.camera = GMSCameraPosition.camera(withLatitude: 54.9044200, 
 longitude: 52.3154000, zoom: 15.0)
 }
}

使用这段代码没有任何反应。我尝试了stackoverflow上的所有方法,但仍然没有任何反应。


你好- 如果从函数中删除 @IBAction 装饰器会发生什么?(您可能需要将其替换为 @objc)。 - Marcus
这种方法也不起作用。 - ildar1989
@ildar1989,这个有什么反馈吗? - Reinier Melian
2个回答

6
只需将你的viewController类指定为GMSMapViewDelegate的代理即可。
override func viewDidLoad() {
    super.viewDidLoad()
    self.mMap.delegate = self
    //....
}

在下面的方法中追踪长按操作...
extension ViewController: GMSMapViewDelegate {
    func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {
        print(coordinate)
    }
}

3

GMSMapView类有许多不同的手势识别器,因此您需要将UIGestureRecognizerDelegate实现添加到您的视图控制器中,并添加此方法shouldRecognizeSimultaneouslyWith

这里是您需要修改的内容

添加

extension ViewController : UIGestureRecognizerDelegate
{
    public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool
    {
        return true
    }
}

添加

longPressRecognizer.delegate = self

以下是代码:longPressRecognizer.minimumPressDuration = 0.5

完整代码:

import UIKit
import GoogleMaps

class ViewController: UIViewController {
@IBOutlet var mMap: GMSMapView!

var longPressRecognizer = UILongPressGestureRecognizer()

@IBAction func longPress(_ sender: UILongPressGestureRecognizer) {
    testTextview.text = "You tapped at YES"
}

override func viewDidLoad() {
    super.viewDidLoad()

 longPressRecognizer = UILongPressGestureRecognizer(target: self, 
 action: #selector(self.longPress))
 longPressRecognizer.minimumPressDuration = 0.5
 longPressRecognizer.delegate = self
 mMap.addGestureRecognizer(longPressRecognizer)

 mMap.isMyLocationEnabled = true 
 mMap.settings.compassButton = true 
 mMap.camera = GMSCameraPosition.camera(withLatitude: 54.9044200, 
 longitude: 52.3154000, zoom: 15.0)
 }
}

extension ViewController : UIGestureRecognizerDelegate
    {
        public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool
        {
            return true
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接