Xcode 如何使用UILongPressGestureRecognitor在用户位置添加pin码?
我正在制作一个在地图上添加pin的应用程序,到目前为止,它一直在用户长按的位置添加pin,但我希望它可以更改并添加到用户位置,但是,我不知道如何更改才能实现,请更正我的代码以使其正常工作? 谢谢,我在下面添加了我的代码:Xcode 如何使用UILongPressGestureRecognitor在用户位置添加pin码?,xcode,swift,Xcode,Swift,我正在制作一个在地图上添加pin的应用程序,到目前为止,它一直在用户长按的位置添加pin,但我希望它可以更改并添加到用户位置,但是,我不知道如何更改才能实现,请更正我的代码以使其正常工作? 谢谢,我在下面添加了我的代码: var uilpgr = UILongPressGestureRecognizer(target: self, action: "action:") uilpgr.minimumPressDuration = 2.0 Map.addGestureRecogn
var uilpgr = UILongPressGestureRecognizer(target: self, action: "action:")
uilpgr.minimumPressDuration = 2.0
Map.addGestureRecognizer(uilpgr)
}
func action(gestureRecognizer:UIGestureRecognizer) {
if gestureRecognizer.state == UIGestureRecognizerState.Began {
var touchPoint = gestureRecognizer.locationInView(self.Map)
var newCoordinate = self.Map.convertPoint(touchPoint, toCoordinateFromView: self.Map)
var location = CLLocation(latitude: newCoordinate.latitude , longitude: newCoordinate.longitude)
这是我正在使用的用户位置代码:
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var userLocation:CLLocation = locations[0] as! CLLocation
var latitude = userLocation.coordinate.latitude
var longitude = userLocation.coordinate.longitude
var coordinate = CLLocationCoordinate2DMake(latitude, longitude)
var latDelta:CLLocationDegrees = 0.01
var lonDelta:CLLocationDegrees = 0.01
var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
var region:MKCoordinateRegion = MKCoordinateRegionMake(coordinate, span)
self.Map.setRegion(region, animated: true)
}
触发长按时,只需向地图添加一个注释对象,该对象是一个轻量级的模型对象,与pin将保存的数据相对应
let annotation = MKAnnotation();
annotation.title = "My location";
annotation.coordinate = self.Map.userLocation.location.coordinate;
self.Map.addAnnotation(annotation);
添加注释后,请确保已注册到地图视图的代理,它将要求您为添加的注释提供视图
func mapView(_ mapView: MKMapView!,
viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView!{
if(annotation is MKUserLocation){
return nil;
}
let pinView = mapView.dequeueReusableAnnotationForIdentifier("MyIdentifier");
let pinAnnotationView = MKPinAnnotationView(annotation,reuseIdentifier:"MyIdentifier");
return pinAnnotationView;
}
我肯定有一些语法问题,但希望您理解其中的逻辑。为用户的位置创建注释。这将触发映射视图的协议方法,并在其中提供附加注释的pin注释视图 不要在action()函数中添加触摸的位置,只需更改它即可添加用户位置的位置(如果可以通过self.Map.userlocation获得),谢谢您的回答@JoshHamet您的意思是这样吗?var touchPoint=gesturecognizer.self.Map.userLocation,如果是这样,则表示UILongPressgesturecognizer没有名为“Map”的成员。谢谢您的回答,但是我确实需要pin,因为我正在使用这些pin做一些事情