当有人使用 Swift 设置 pin 时,实现自定义 MKAnnotationView 的最佳方法是什么?

What is the best way to implement a custom MKAnnotationView when someone sets a pin using Swift?

当用户点击图钉时,MKAnnotationView 出现,但它非常有限。我创建了一个自定义按钮,但有没有办法自定义从图钉出现的整个视图?这是我目前所拥有的。

    func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {


    let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "location")
    annotationView.canShowCallout = true

    let btn = UIButton(type: .Custom) as UIButton
    btn.frame = CGRectMake(50, 60, 60, 50)
    btn.setTitle("button", forState: .Normal)
    btn.titleLabel?.textAlignment = NSTextAlignment.Center
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center

    btn.layer.borderColor = UIColor.blueColor().CGColor
    btn.layer.borderWidth = 0.5

    btn.backgroundColor = UIColor.redColor()

    annotationView.rightCalloutAccessoryView = btn

    return annotationView
}

您应该能够以编程方式构建自己的 UIView,并将它们分配给 MKPinAnnotationView 的 leftCalloutAccessoryViewrightCalloutAccessoryViewdetailCalloutAccessoryView 属性。 UIButton 是 UIView 的子类,所以您到目前为止所拥有的理论上应该可以工作。

如果您坚持使用这 3 个属性并使用每个 UIView 的框架 属性,您应该能够执行相当多的自定义。还要记住每个 UIView 可以有多个子视图。

"Hacky" 解决方案

如果您真的想制作一个完全可自定义的标注,您可能需要在图钉本身上设置一个点击手势识别器,这将导致您的自定义标注视图出现。但是,我建议不要使用这种 more "hacky" 方法,因为它可能会导致标注出现更多故障。不幸的是,我认为没有办法直接分配自定义标注视图。

编辑:正如 Rob 所建议的,您可以在 MKMapViewDelegate 中实现 didSelectAnnotationView 以生成自定义标注视图而不是点击手势识别器。这是一个更好但仍然 "hacky" 的解决方案——它会比股票标注视图更容易出错。