【问题标题】:Create long press gesture recognizer with annotation pin使用注释针创建长按手势识别器
【发布时间】:2016-11-28 12:27:09
【问题描述】:

到目前为止,我所做的是创建地图。然后显示用户位置并将其居中,以便在旅行(汽车等)时地图居中

但现在我想添加一个长按手势,这样如果用户进行输入,就会删除一个 pin。我一直在努力学习教程并且模拟器崩溃了。

如何添加 longPressGesturerecognizer 以便它在我的 mapView 上放置一个图钉。

这是我的代码-

import UIKit
import MapKit
import CoreLocation

class Page2: UIViewController, MKMapViewDelegate,  CLLocationManagerDelegate{

    @IBOutlet var mapView: MKMapView!
    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()
        //blue dot on the map
        self.mapView.showsUserLocation = true
        //tracking mode on
        self.mapView.userTrackingMode = .follow
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // location Manager Delegate center user on map
    private func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

        let location = locations.last
        let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: (location?.coordinate.longitude)!)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005)) //zoom on map
        self.mapView.setRegion(region, animated: true)
        self.locationManager.stopUpdatingLocation()
    }

    // print errors
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error){
        print("Errors: " + error.localizedDescription)
    }
}

【问题讨论】:

    标签: swift swift3 mkmapview xcode8 uilongpressgesturerecogni


    【解决方案1】:

    首先在Swift 3 中CLLocationManagerDelegate 方法的locationManager(_:didUpdateLocations:) 的签名被改变了,所以你需要改变那个方法如下。

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
         //your code and don't forgot to remove private
    }
    

    您可以像这样使用longGesturemapView,首先在mapView 中使用addGestureRecognizerviewDidLoad 中。

    let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(addAnnotationOnLongPress(gesture:)))
    longPressGesture.minimumPressDuration = 1.0
    self.mapView.addGestureRecognizer(longPressGesture)
    

    现在为 UILongPressGestureRecognizer 添加操作。

    @objc func addAnnotationOnLongPress(gesture: UILongPressGestureRecognizer) {
    
        if gesture.state == .ended {
            let point = gesture.location(in: self.mapView)
            let coordinate = self.mapView.convert(point, toCoordinateFrom: self.mapView)
            print(coordinate)
            //Now use this coordinate to add annotation on map.
            var annotation = MKPointAnnotation()
            annotation.coordinate = coordinate
            //Set title and subtitle if you want
            annotation.title = "Title" 
            annotation.subtitle = "subtitle" 
            self.mapView.addAnnotation(annotation)
        }
    }
    

    【讨论】:

    • 谢谢我似乎在这一行得到了这个错误 let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(addAnnotationOnLongPress(gesture:))) use of local variable 'addAnnotationOnLongPress(gesture:) ' 在其声明之前
    • 现在唯一看到的是坐标被记录在输出中,但它没有掉任何针
    • 这部分在这里? //现在使用这个坐标在地图上添加注释。
    • 感谢您的帮助 我在最后一行出现错误 self.mapView.addAnnotation(myHomePin) 错误:使用未解析的标识符 'myHomePin' 将尝试解决此问题
    • @sabrefm1 这是拼写错误检查编辑答案:)
    【解决方案2】:

    您也可以使用轻击手势来放置图钉。

    添加点击手势

        let tapGesture = UITapGestureRecognizer(target: self, action:#selector(AddressViewController.handleTap(_:)))
        tapGesture.delegate = self
        mapView.addGestureRecognizer(tapGesture)
    

    在手势上放置图钉

    func handleTap(_ sender: UIGestureRecognizer)
    {
      if sender.state == UIGestureRecognizerState.ended {
    
            let touchPoint = sender.location(in: mapView)
            let touchCoordinate = mapView.convert(touchPoint, toCoordinateFrom: mapView)
            let annotation = MKPointAnnotation()
            annotation.coordinate = touchCoordinate
            annotation.title = "Event place"
            mapView.removeAnnotations(mapView.annotations)
        mapView.addAnnotation(annotation) //drops the pin
      }
    }
    

    【讨论】:

    • @RohirParsana 很好的答案。但是我如何获得纬度和经度?我想将这些放入变量中。最好的,Philip 刚刚知道 :-) touchCoordinate 返回纬度和经度。我可以单独得到这些,例如打印(触摸坐标。纬度)
    【解决方案3】:

    我认为这个更新的小代码有助于其他人通过长按放置引脚来实现注释:

        import UIKit
        import MapKit
        class ViewController: UIViewController, MKMapViewDelegate {
    
            @IBOutlet weak var map: MKMapView!
    
            override func viewDidLoad() {
                super.viewDidLoad()
    
                let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(longPressed(gestureRecognized:)))
    
                //long press (2 sec duration)
                uilpgr.minimumPressDuration = 2
                map.addGestureRecognizer(uilpgr)   
            }
    
            func longPressed(gestureRecognized: UIGestureRecognizer){
                let touchpoint = gestureRecognized.location(in: self.map)
                let location = map.convert(touchpoint, toCoordinateFrom: self.map)
    
                let annotation = MKPointAnnotation()
                annotation.title = "Latitude: \(location.latitude)"
                annotation.subtitle = "Longitude: \(location.longitude)"
                annotation.coordinate = location
                map.addAnnotation(annotation)
    
    
            }
    
            override func didReceiveMemoryWarning() {
                super.didReceiveMemoryWarning()
                // Dispose of any resources that can be recreated.
            }
    
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多