如何在Swift中向MKPointAnnotation添加按钮

Ste*_*eve 4 annotations uibutton mkmapview ios swift

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

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!)
    }
Run Code Online (Sandbox Code Playgroud)

nat*_*0va 7

这可以通过添加UIButton来rightCalloutAccessoryView实现MKPinAnnotationView.这是一个例子:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是这样:

注释视图按钮

希望对你有所帮助!