Swift - Coordinate is unavailable: APIs deprecated as of iOS 7

僤鯓⒐⒋嵵緔 提交于 2019-12-11 12:48:08

问题


I'm trying to iterate through an array of annotations by getting by self.mapView.annotations.

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.

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)

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.


回答1:


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)
}

(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.)

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)
}


来源:https://stackoverflow.com/questions/27195494/swift-coordinate-is-unavailable-apis-deprecated-as-of-ios-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!