首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用UILongPressGestureRecognizer swift3向UILongPressGestureRecognizer swift3添加标记

用UILongPressGestureRecognizer swift3向UILongPressGestureRecognizer swift3添加标记
EN

Stack Overflow用户
提问于 2017-04-15 21:13:56
回答 1查看 322关注 0票数 0

我想用UILongPressGestureRecognizer添加标记,但是我的代码不起作用,我做错了什么?

代码语言:javascript
复制
func setupGesture() {
        let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(action))
        longPressRecognizer.minimumPressDuration = 1.0
        mapView.addGestureRecognizer(longPressRecognizer)
    }

    func action(recognizer: UILongPressGestureRecognizer) {
        if (recognizer.state == .ended) {
            DispatchQueue.main.async {
                let longPressPoint = recognizer.location(in: mapView)
                let coordinate = self.mapView.projection.coordinate(for: longPressPoint)
                let marker = GMSMarker(position: coordinate)
                marker.title = "Hello World"
                marker.map = mapView
            }
        }
    }

这个方法不太管用。

代码语言:javascript
复制
extension MapViewController: GMSMapViewDelegate {
    func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {
        DispatchQueue.main.async {
            let marker = GMSMarker(position: coordinate)
            marker.title = "Hello World"
            marker.map = mapView
        }
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-17 11:26:08

这段代码对我来说很好。您不需要UILongTapGestureRecogniser,只需设置mapView委托并使用didLongTapAt委托函数即可。

代码语言:javascript
复制
class ViewController: UIViewController {

    var mapView: GMSMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.mapView.delegate = self
    }

    override func loadView() {
        // Create a GMSCameraPosition that tells the map to display the
        // coordinate -33.86,151.20 at zoom level 6.
        let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
        self.mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        view = mapView

        // Creates a marker in the center of the map.
        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
        marker.title = "Sydney"
        marker.snippet = "Australia"
        marker.map = mapView
    }
}

extension ViewController: GMSMapViewDelegate {
    func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {
        let marker = GMSMarker()
        marker.position = coordinate
        marker.title = ""
        marker.snippet = ""
        marker.map = mapView
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43431345

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档