地图工具包注释按钮无效(swift3)

时间:2017-01-23 02:59:03

标签: ios swift button swift3 mapkit

我正在尝试按照本教程https://www.hackingwithswift.com/read/19/3/annotations-and-accessory-views-mkpinannotationview进行操作。我无法通过注释来显示信息按钮。我不知道是否必须在故事板中加入一些内容。

Here is a picture of the storyboard with the button selected

无论如何,按钮没有显示在注释中。只是城市名称。以下是我的代码。缺少按钮的图片:

missing button

    import MapKit
import UIKit

class Capital: NSObject, MKAnnotation {
var title: String?
var coordinate: CLLocationCoordinate2D
var info: String

init(title: String, coordinate: CLLocationCoordinate2D, info: String) {
    self.title = title
    self.coordinate = coordinate
    self.info = info
}
}

class ViewController: UIViewController {
let btn = UIButton(type: .detailDisclosure)


@IBOutlet var mapView: MKMapView!
override func viewDidLoad() {
    super.viewDidLoad()
    let london = Capital(title: "London", coordinate: CLLocationCoordinate2D(latitude: 51.507222, longitude: -0.1275), info: "Home to the 2012 Summer Olympics.")

    mapView.addAnnotations([london])
}

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    // 1
    let identifier = "Capital"

    // 2
    if annotation is Capital {
        // 3
        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)

        if annotationView == nil {
            //4
            annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            annotationView!.canShowCallout = true

            // 5
            let btn = UIButton(type: .detailDisclosure)
            annotationView!.rightCalloutAccessoryView = btn
        } else {
            // 6
            annotationView!.annotation = annotation
        }

        return annotationView
    }

    // 7
    return nil
}

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    let capital = view.annotation as! Capital
    let placeName = capital.title
    let placeInfo = capital.info

    let ac = UIAlertController(title: placeName, message: placeInfo, preferredStyle: .alert)
    ac.addAction(UIAlertAction(title: "OK", style: .default))
    present(ac, animated: true)
}}

0 个答案:

没有答案