sab*_*fm1 1 mkmapview swift uilongpressgesturerecogni swift3 xcode8
到目前为止我所做的是创建一张地图.然后显示用户位置并居中,以便地图在旅行时居中(汽车等)
但是现在我想添加一个长按手势,这样如果用户输入一个引脚就会被丢弃.我一直在努力学习教程和模拟器崩溃.
我如何添加,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)
}
}
Run Code Online (Sandbox Code Playgroud)
首先在Swift 3 中更改CLLocationManagerDelegate方法的签名locationManager(_:didUpdateLocations:),因此您需要更改该方法,如下所示.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//your code and don't forgot to remove private
}
Run Code Online (Sandbox Code Playgroud)
你可以用longGesture与mapView这样的,首先addGestureRecognizer在你mapView的viewDidLoad.
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(addAnnotationOnLongPress(gesture:)))
longPressGesture.minimumPressDuration = 1.0
self.mapView.addGestureRecognizer(longPressGesture)
Run Code Online (Sandbox Code Playgroud)
现在为此添加操作UILongPressGestureRecognizer.
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)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3979 次 |
| 最近记录: |