0

I'm trying to resize a UIImage to fit inside a map view's annotation in the leftCalloutAccessoryView slot. I've attempted (poorly) to add constraints but the image is not showing up - without the constraints it shows up, but it's far too large. Now with them, it doesn't appear at all, I'm thinking because it's been resized out of the view. I tried adding a leftAnchor and topAnchor but got an error because I'm not entirely sure what I should be pinning it to - the accessory view? Annotation view? Anyway here's the code thus far:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    let identifier = "Restaurants"

    if annotation is Restaurants {
        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)

        if annotationView == nil {
            annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            annotationView!.canShowCallout = true

            let infoButton = UIButton(type: .detailDisclosure)
            let imgView = UIImageView(image: UIImage(named: "TTT"))

            // constraints
            imgView.translatesAutoresizingMaskIntoConstraints = false
            imgView.widthAnchor.constraint(equalToConstant: 20).isActive = true
            imgView.heightAnchor.constraint(equalToConstant: 20).isActive = true

            annotationView!.rightCalloutAccessoryView = infoButton
            annotationView!.leftCalloutAccessoryView = imgView
        } else {
            annotationView!.annotation = annotation
        }
        return annotationView
    }
    return nil
}

Do I just need to be adding side and top anchors, or is there a different way of going about this entirely?

Thanks!

1 Answer 1

1

You can try to set the UIImageView size to the created MKPinAnnotationView

and then call aspect fit on it like this:

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: annotationView!.frame.height, height: annotationView!.frame.height))

imageView.image = UIImage(named: "TTT")
imageView.contentMode = .scaleAspectFit

annotationView!.leftCalloutAccessoryView = imageView
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.