【发布时间】:2015-01-26 16:51:19
【问题描述】:
我有 2 个注释要显示在 mapview 上,但无法将 maprect 设置为在屏幕上显示所有注释而不需要用户缩小。
我尝试使用showAnnotations,但没有运气。任何人都能够在 Swift 和 Xcode 6.1.1 中做到这一点?
这是我的代码:
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet var map: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
var mapView = map
// 1
let point1 = CLLocationCoordinate2D(latitude: 38.915565, longitude: -77.093524)
let point2 = CLLocationCoordinate2D(latitude: 38.890693, longitude: -76.933318)
//2
let annotation = MKPointAnnotation()
annotation.setCoordinate(point1)
annotation.title = "point1"
map.addAnnotation(annotation)
let annotation2 = MKPointAnnotation()
annotation2.setCoordinate(point2)
annotation2.title = "point2"
map.addAnnotation(annotation2)
//3
// option1: set maprect to cover all annotations, doesn't work
var points = [annotation, annotation2]
var rect = MKMapRectNull
for p in points {
let k = MKMapPointForCoordinate(p.coordinate)
rect = MKMapRectUnion(rect, MKMapRectMake(k.x, k.y, 0.1, 0.1))
println("result: x = \(rect.origin.x) y = \(rect.origin.y)")
}
map.setVisibleMapRect(rect, animated: true)
// option 2: using showAnnotations, doesn't work
//map.showAnnotations(points, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
这是我目前得到的:
这是我期望看到的:
感谢您的帮助。
【问题讨论】:
-
你能解释一下你说
showAnnotations“不起作用”的确切含义吗?发生什么了?对于setVisibleMapRect,您可能需要应用 inset(参见 stackoverflow.com/a/22070026/467105 的示例)。此外,您已经实现了viewForAnnotation,它显示了注释的自定义图像,但在您“预期”的屏幕截图中,它显示了默认的红色引脚。为什么你会期待默认的红色图钉? -
Anna,我对 showAnnotations 的“不起作用”的意思是它没有像预期的屏幕那样显示所有引脚。
-
带有 showAnnotations 的代码看起来不错。如果您更喜欢 setVisibleMapRect,请添加一个插图。 在测试缩放时完全注释掉 viewForAnnotation 方法。修复缩放后,使用 viewForAnnotation 解决问题。 如果没有显示任何引脚,请确保正在调用 viewForAnnotation(确保已设置地图委托,确保图像文件存在)。
-
安娜,如果你说“showAnnotations 看起来不错”,为什么它不起作用?你试过那个代码了吗?
-
是的,我尝试了问题中发布的代码并且它有效。 showAnnotations 工作没有任何变化。对于 setVisibileMapRect,需要应用一个 inset,这样注释就不会完全位于屏幕边缘。
标签: swift mkmapview mkannotation mkmaprect