0

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

    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
}
4

1 回答 1

2

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

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

“哈克”解决方案

如果你真的想制作一个完全可定制的标注,你可能需要在图钉本身上设置一个点击手势识别器,这会导致你的自定义标注视图出现。但是,我建议不要使用这种更“hacky”的方法,因为它可能会导致标注更加错误。不幸的是,我不相信有直接分配自定义标注视图的方法。

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

于 2016-02-13T16:39:43.883 回答