根据this post,只要您拨打addAnnotation
方法,就会调用mapView:viewForAnnotation
但是,以下代码只调用mapView:viewForAnnotation
一次。我有几个注释,但"视图称为"只印了一次。我想这与线程有关吗?
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, UITextFieldDelegate, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet var searchtext: UITextField!
@IBOutlet var map: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.searchtext.delegate = self
locationManager.delegate = self
self.map.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func textFieldDidBeginEditing(textField: UITextField!) { //delegate method
var allAnnotations = self.map.annotations
self.map.removeAnnotations(allAnnotations)
}
func textFieldShouldReturn(textField: UITextField!) ->Bool {
textField.resignFirstResponder()
//...
let session = NSURLSession.sharedSession()
var task = session.dataTaskWithURL(url!, completionHandler: { (date, response, error) -> Void in
if (error != nil) {
println(error)
}else {
var placenum = 0
//placenum is to see if all the places are in the visible rect. If so I will use showAnnotations to zoom (in) to the best-fitted view show them. If not, I will only show these in the visible rect
for place in places {
//...
if (regionContains(self.map.region, coordinate)) {
placenum = placenum+1
}
self.map.addAnnotation(annotation)
}
if (placenum==places.count) {
self.map.showAnnotations(self.map.annotations, animated: true)
}
}
})
task.resume()
return true
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
//...
self.map.setRegion(region, animated: false)
locationManager.stopUpdatingLocation()
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
println("view called")
return nil
}
答案 0 :(得分:3)
另外请确保将mapview的委托属性设置为self。
mapview.delegate = self
您也可以使用Connection Inspector(Interface Builder)将mapview的委托出口连接到ViewController
答案 1 :(得分:2)
简而言之,当注释落在地图视图的可见部分内时,会调用viewForAnnotation
。也就是说,(a)注释已添加到地图视图中,它随region
或(b)region
更改而下降,以便之前未显示的注释是。
顺便说一下,completionHandler
的{{1}}将不在主线程上。必须将任何UI更新显式分派回主线程,例如
dataTaskWithURL
我建议确保在主线程上发生与地图视图的交互,如上所示。
顺便提一下,请记住,如果您在地图上显示用户位置,那么本身会导致dispatch_async(dispatch_get_main_queue()) {
for place in places {
//...
placenum = placenum + 1
self.map.addAnnotation(annotation)
}
self.map.showAnnotations(self.map.annotations, animated: true)
}
被调用。因此,如果您只看到一次调用,则可能需要确认viewForAnnotation
是annotation
还是您添加的其中一个注释。