Swift - 坐标不可用:API 从 iOS 7 开始弃用 [英] Swift - Coordinate is unavailable: APIs deprecated as of iOS 7
问题描述
我正在尝试通过 self.mapView.annotations
获取注释数组.
I'm trying to iterate through an array of annotations by getting by self.mapView.annotations
.
我遇到的问题是我收到一个错误,因为坐标不可用:从 iOS 7 及更早版本开始弃用的 API 对 Swift 不可用.
The issue I'm having is that i'm getting an error because Coordinate is unavailable: APIs deprecated as of iOS 7 and earlier are unavailable to Swift.
有什么想法可以解决这个问题吗?我查看了 iOS 开发人员库,但找不到任何方法来获取每个注释的坐标.
Any ideas how I can fix this? I have a look at the iOS developer library but I couldn't find any way of getting the coordinate for each annotation.
var zoomRect:MKMapRect = MKMapRectNull;
for (index,annotation) in enumerate(self.mapView.annotations) {
var annotationPoint:MKMapPoint = MKMapPointForCoordinate(annotation.coordinate)
var pointRect:MKMapRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1);
zoomRect = MKMapRectUnion(zoomRect, pointRect);
}
self.mapView.setVisibleMapRect(zoomRect, animated: true)
此代码的主要思想是将地图居中,以便用户能够看到所有注释.我在 Objective C 中得到了这段代码(来自 SO 的另一个问题)并将其转换为 Swift,但仍然没有运气.
The main idea for this code is to center the map so that users will be able to see all the annotations. I got this code in Objective C (another question from SO) and converted it to Swift but still having no luck.
推荐答案
MKMapView
的annotations
属性返回[AnyObject]!
并且 AnyObject
没有 coordinate
属性.您必须转换为 [MKAnnotation]
数组:
The annotations
property of MKMapView
returns [AnyObject]!
and AnyObject
does not have a coordinate
property.
You have to cast to an [MKAnnotation]
array:
var zoomRect = MKMapRectNull
for annotation in self.mapView.annotations as [MKAnnotation] {
let annotationPoint = MKMapPointForCoordinate(annotation.coordinate)
let pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1)
zoomRect = MKMapRectUnion(zoomRect, pointRect)
}
(代码中的显式类型注释不是必需的,变量循环内部实际上是常量,因此您可以使用 let
声明它们.)
(The explicit type annotation in your code are not necessary, and the variables
inside the loop are in fact constants, so you can declare them with let
.)
请注意,您可以将 for 循环替换为 reduce 操作:
Note that you could replace the for-loop by a reduce operation:
let zoomRect = reduce(self.mapView.annotations as [MKAnnotation], MKMapRectNull) {
rect, annotation in
let annotationPoint = MKMapPointForCoordinate(annotation.coordinate)
let pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1)
return MKMapRectUnion(rect, pointRect)
}
这篇关于Swift - 坐标不可用:API 从 iOS 7 开始弃用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!