How to add two or more buttons to annotationView: MKAnnotationView?

前端 未结 2 1070

I want to have a MKAnnotationView to my pins on map (using MapKit) with next attributes:

1) image

2) details button

3) another details button

<
2条回答
  •  长发绾君心
    2021-01-14 04:18

    You can use detailCalloutAccessoryView of the MKAnnotationView to achieve that.

    Example how to do extension of the MKAnnotationView with UIStackView:

    extension MKAnnotationView {
    
        func conteiner(arrangedSubviews: [UIView]) {
            let stackView = UIStackView(arrangedSubviews: arrangedSubviews)
            stackView.axis = .vertical
            stackView.distribution = .fillEqually
            stackView.alignment = .fill
            stackView.spacing = 5
            stackView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleLeftMargin, .flexibleBottomMargin, .flexibleWidth, .flexibleHeight]
            stackView.translatesAutoresizingMaskIntoConstraints = false
    
            self.detailCalloutAccessoryView = stackView
        }
    }
    

    And how to implement this:

    extension ViewController: MKMapViewDelegate {
        func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    
            let annotationIdentifier = "AnnotationIdentifier"
    
            var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier)
    
            if annotationView == nil {
                annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
                annotationView!.canShowCallout = true
                annotationView!.conteiner(arrangedSubviews: [UIButton(type: .detailDisclosure), UIButton(type: .detailDisclosure), UIButton(type: .detailDisclosure)])
    
            }
            else {
                annotationView!.annotation = annotation
            }
    
            return annotationView
        }
    }
    

    Result:

提交回复
热议问题