Refresh MKAnnotationView on a MKMapView

前端 未结 7 481
天涯浪人
天涯浪人 2021-01-31 09:27

I\'d like to a-synchronically load images for my custom MKAnnotationView; I\'m already using the EGOImageView-framework (it goes very well with UITableViews), but I fail to make

7条回答
  •  遇见更好的自我
    2021-01-31 09:50

    I wanted to refresh user location pin with new selected avatar. I found another fast solution for that case. I have 2 screens. The first one is for selecting avatar and the second is for displaying user on map.

    swift 5 You can change user location image by creating MKAnnotationView

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    
        if annotation is MKUserLocation {
            let userIdentifier = "UserLocation"
            var userView = mapView.dequeueReusableAnnotationView(withIdentifier: userIdentifier)
            if userView == nil {
                userView = MKAnnotationView(annotation: annotation, reuseIdentifier: userIdentifier)
            } else {
                userView?.annotation = annotation
            }
    
            userView!.image = UIImage(named: "avatar1") //your image
    
            return userView
        }
    
        return nil
     }
    

    So if user will change avatar to something else, for example to "avatar2" it won't refresh.

    In order to refresh user location image i added this code in viewWillAppear()

     self.mapView.showsUserLocation = false
     self.mapView.showsUserLocation = true
    

提交回复
热议问题