MKMapView zoom to users location on viewDidLoad?

前端 未结 10 1711
有刺的猬
有刺的猬 2021-01-30 16:40

I\'m trying to zoom a map into the user\'s current location once the view loads, but I\'m getting the error \"** * Terminating app due to uncaught exception \'NSInvalidA

10条回答
  •  旧时难觅i
    2021-01-30 17:38

    By far the easiest way is to use mapView.showAnnotations in didUpdateUserLocation:

    func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) {
        mapView.showAnnotations([userLocation], animated: true)
    }
    

    That's all!

    MKUserLocation conforms to the MKAnnotation protocol. Pass the userLocation as an array, the showAnnotations method will let the mapView zoom in on a region plus padding spanning the array of MKAnnotations,in this case it's just the userLocation. Works for me.

    If you only want to zoom in once, use a initialUserLocation property to check whether the initial property was already set. I don't like using dispatch_once at all for that sort of thing

提交回复
热议问题