如何在Swift中向MKPointAnnotation添加按钮

时间:2017-01-05 22:35:37

标签: ios swift uibutton annotations mkmapview

我希望能够在地图注释上放置一个按钮和标签。标题,副标题和坐标的注释完美无缺,但我无法显示按钮。

func drawEvents(_ loc: CLLocation, title1: String)
    {
        mapView.delegate = self//
        let center = CLLocationCoordinate2D(latitude: loc.coordinate.latitude, longitude: loc.coordinate.longitude)
        let lat: CLLocationDegrees = center.latitude
        let long: CLLocationDegrees = center.longitude
        self.pointAnnotation1 = MKPointAnnotation()
        self.pointAnnotation1.title = title1
        self.pointAnnotation1.subtitle = "Event"
        self.pointAnnotation1.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
        self.pinAnnotationView = MKPinAnnotationView(annotation: self.pointAnnotation1, reuseIdentifier: nil)
        self.mapView.addAnnotation(self.pinAnnotationView.annotation!)
    }

1 个答案:

答案 0 :(得分:6)

这可以通过向MKPinAnnotationView的{​​{1}}添加UIButton来实现。 这是一个例子:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if !(annotation is MKUserLocation) {
        let pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: String(annotation.hash))

        let rightButton = UIButton(type: .contactAdd)
        rightButton.tag = annotation.hash

        pinView.animatesDrop = true
        pinView.canShowCallout = true
        pinView.rightCalloutAccessoryView = rightButton

        return pinView
    }
    else {
        return nil
    }
}

这就是它的样子:

Annotation View Button

希望能帮到你!