调整图像大小以适应 MapView 的 leftCalloutAccessoryView

Resizing image to fit in MapView's leftCalloutAccessoryView

我正在尝试调整 UIImage 的大小以适应 leftCalloutAccessoryView 插槽中地图视图的注释。我尝试(很差地)添加约束但图像没有显示 - 没有显示的约束,但它太大了。现在有了它们,它根本就没有出现,我在想,因为它已经被调整到视图之外了。我尝试添加 leftAnchortopAnchor 但出现错误,因为我不完全确定我应该将其固定到什么 - 附件视图?注释视图?到目前为止,这里是代码:

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
}

我是否只需要添加侧锚和顶锚,或者是否有完全不同的方法来解决这个问题?

谢谢!

您可以尝试将 UIImageView 大小设置为创建的 MKPinAnnotationView

然后调用 aspect fit 像这样:

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