【发布时间】:2015-04-13 16:28:38
【问题描述】:
根据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
}
【问题讨论】:
-
我不确定
if (placenum==places.count)模式的意图,但对我来说这似乎是不必要和多余的。你怎么能走到那个循环的尽头,而这两个不相等?而且,如果由于某种原因没有添加其中一个注释,您为什么不想显示那些注释呢? -
@Rob 我过度简化了代码。相关部分现已添加回来。如果“坐标”落在当前地图视图区域,则 placenum++。
-
所以,我还以为你只想要
if (placenum > 0),不是吗?但是,如果您只添加可见矩形内的注释,则根本不需要showAnnotations,对吗?showAnnotations的目的是更改地图视图以适应您添加的注释,但如果它们都可见,则不需要更改,对吧? -
@Rob
placenum是看是否所有的地方都在可见的矩形内。如果是这样,我将使用 showAnnotations 放大(放大)到最适合的视图显示它们。如果没有,我只会在可见的矩形中显示这些,当前代码不起作用。我必须点击地图才能触发添加注释。我计划通过在可见矩形中创建另一个注释列表并将showAnnotations与列表一起使用来修复它。另一方面,你的回答观察1似乎指向了另一种方式...... -
首先,一定要把所有的地图内容移到主线程,这样一些奇怪的行为可能会消失。其次,我只提出了“何时缩放”逻辑问题,因为这对我来说似乎是倒退的,但听起来这是一个有意识的决定,所以在这个分数上做任何你想做的事情。祝你好运!
标签: swift mapkit mapkitannotation