如何在 Swift 中向 MKPointAnnotation 添加按钮 [英] How to add button to MKPointAnnotation in Swift

查看:36
本文介绍了如何在 Swift 中向 MKPointAnnotation 添加按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在我的地图注释上放置一个按钮和标签.带有标题、副标题和坐标的注释效果很好,但我无法显示按钮.

I want to be able to put a button and label on my map annotation. The annotation with the title, subtitle, and coordinates works perfectly, but I can't get a button to appear.

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!)
    }

推荐答案

这可以通过向 MKPinAnnotationViewrightCalloutAccessoryView 添加一个 UIButton 来实现.下面是一个例子:

This can be accomplished by adding a UIButton to the rightCalloutAccessoryView of the MKPinAnnotationView. Here is an example:

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

这就是它的样子:

希望能帮到你!

这篇关于如何在 Swift 中向 MKPointAnnotation 添加按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆