【发布时间】:2016-12-23 03:45:05
【问题描述】:
我有一些使用MKMapView 和MKPointAnnotation 的经验,我曾经在地图上放置一些图钉。
这次我想更进一步,使用MKPinAnnotationView,写一个标签和一些别针。
不幸的是,它并没有像我预期的那样工作。
这是我想做的:
我有一张地图(一个 MKMapView 对象),当我触摸它时,我在触摸点上放了一个大头针,然后执行一些计算,这给了我地图上的第二个点。我放了第二个图钉(位于第二个点),在最后一个图钉上我想贴一个标签,说“Hello Second!”。
以下是相关代码:
class ViewController: UIViewController, MKMapViewDelegate {
var mapView:MKMapView!, touchPoint,secondPoint:MKPointAnnotation!
override func viewDidLoad() {
super.viewDidLoad()
mapView = MKMapView()
...........
let mapTap = UITapGestureRecognizer(target: self,
action: #selector(ViewController.mapTouchHandler))
mapView.addGestureRecognizer(mapTap)
}
func mapTouchHandler(gesture:UITapGestureRecognizer) {
...........
// Compute map coordinates for the touch point (tapGeoPoint).
if touchPoint == nil {
touchPoint = MKPointAnnotation()
mapView.addAnnotation(touchPoint);
}
touchPoint.coordinate = CLLocationCoordinate2D(latitude: tapGeoPoint.latitude,
longitude: tapGeoPoint.longitude)
...........
computeSecondPoint(url: someComputedURL)
}
func computeSecondPoint(url searchURL:String) {
let reqURL = NSURL(string: searchURL)!, session = URLSession.shared,
task = session.dataTask(with: reqURL as URL) {
(data: Data?, response: URLResponse?, error: Error?) in
if error == nil {
do {let allData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSArray
.................
// Compute map coordinates for the second point (secondPointCoord).
if self.secondPoint == nil {
self.secondPoint = MKPointAnnotation()
self.mapView.addAnnotation(self.secondPoint)
}
DispatchQueue.main.async {
() -> Void in
self.secondPoint.coordinate = CLLocationCoordinate2D(latitude: secondPointCoord.latitude,
longitude: secondPointCoord.longitude)
self.secondPoint.title = "Hello Second!"
}
} catch let error as NSError {print(error.localizedDescription)}
} else {
print("Error inside \(#function):\n\(error)")
}
}
task.resume()
}
func mapView(_ mapView: MKMapView,
viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "pin"
var view: MKPinAnnotationView
if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
as? MKPinAnnotationView {
dequeuedView.annotation = annotation
view = dequeuedView
} else {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 0)
}
return view
}
}
现在发生的情况是,引脚按预期放置,但我在第二个上看不到任何标签。 我还注意到,如果我点击第二个大头针恰好在的位置(在这种情况下,第二个大头针将保持在同一个地方),那么标签就会出现(就像它应该总是做的那样)。如果我再次点击(不是那么近),那么标签会再次消失(尽管它不应该)。
我的代码(上图)中有什么不正确的地方吗? 任何相关提示将不胜感激。
【问题讨论】:
标签: ios swift3 mkmapview mkpinannotationview mkmapviewdelegate