この投稿によるとaddAnnotation
、メソッド を呼び出すたびに、mapView:viewForAnnotation
呼び出されます
ただし、次のコードはmapView:viewForAnnotation
1 回だけ呼び出されます。いくつかの注釈がありますが、「呼び出されたビュー」は一度だけ印刷されました。ひょっとして、スレと関係あるのかな?
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
}