设置自定义 MKAnnotationView 的中心

Set the center of custom MKAnnotationView

我正在使用自定义 MKAnnotationView。我用的是autolayouts,效果很好,但是注解视图的位置(框架)不合适。

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView)
{
    if view.annotation is MKUserLocation
    {
        return
    }

    let starbucksAnnotation = view.annotation as! LiquorLocation
    let views = Bundle.main.loadNibNamed("CustomCalloutView", owner: nil, options: nil)
    let calloutView = views?[0] as! CustomCalloutView
    calloutView.labelLiquorShopName.text = starbucksAnnotation.title
    calloutView.labelLiquorShopAddress.text = starbucksAnnotation.address
    calloutView.labelLiquorShopAwayDistance.text = starbucksAnnotation.locationKmAway
    calloutView.imageViewLiquorShop.image = starbucksAnnotation.liquorShopIcon


    calloutView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(calloutView)
    mapView.setCenter((view.annotation?.coordinate)!, animated: true)
}

我做错了什么?我想将注释视图居中放置在图钉的顶部。

Autolayouts 再次拯救我的一天。我在标注视图和视图 (MKAnnotationView) 之间添加了布局约束。我在 didSelect 方法中的 view.addSubview(calloutView) 下面写下几行。

let horizontalConstraint = NSLayoutConstraint(item: calloutView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
        let verticalConstraint = NSLayoutConstraint(item: calloutView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)
        let widthConstraint = NSLayoutConstraint(item: calloutView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: calloutView.frame.size.width)
        view.addConstraints([horizontalConstraint, verticalConstraint, widthConstraint])