添加按钮到MKPointAnnotation

时间:2015-10-16 15:11:49

标签: swift mkpointannotation

当我尝试在注释中添加按钮时遇到问题。

在我提出这个问题之前,我已经在以下页面中搜索了答案: How to add a button to the MKPointAnnotation?Adding a button to MKPointAnnotation? 等等 但是所有人都无法帮助我。

这是尝试做的事情:

var annotation1 = MKPointAnnotation()
annotation1.setCoordinate(locationKamer1)
annotation1.title = "Title1"
annotation1.subtitle = "Subtitle1"
// here i want to add a button which has a segue to another page.
mapView.addAnnotation(annotation1)

不知道我尝试做的事情是否有效。 我第一次尝试使用swift。

希望有人可以帮助我:)。

提前致谢!

1 个答案:

答案 0 :(得分:3)

第一个链接中的答案基本上是正确的,但需要为Swift 2更新。

底线,在回答您的问题时,您不会在创建注释时添加按钮。在viewForAnnotation中创建注释视图时,可以创建按钮。

所以,你应该:

  1. 将视图控制器设置为地图视图的委托。

  2. 使视图控制器符合地图视图委托协议,例如:

    class ViewController: UIViewController, MKMapViewDelegate { ... }
    
  3. 通过 control 从视图控制器(而不是按钮)向下一个场景添加一个segue,使用地图视图从场景上方的视图控制器图标拖动到下一个场景:< / p>

    enter image description here

    然后选择segue然后给它一个故事板标识符(在我的例子中为“NextScene”,尽管你应该使用更具描述性的名称):

    enter image description here

  4. 实施viewForAnnotation以添加按钮作为正确的附件。

    func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
        var view = mapView.dequeueReusableAnnotationViewWithIdentifier(annotationIdentifier)
        if view == nil {
            view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
            view?.canShowCallout = true
            view?.rightCalloutAccessoryView = UIButton(type: .DetailDisclosure)
        } else {
            view?.annotation = annotation 
        }
        return view
    }
    
  5. 实施calloutAccessoryControlTapped,其中(a)捕获哪个注释被点击; (b)启动segue:

    var selectedAnnotation: MKPointAnnotation!
    
    func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
        if control == view.rightCalloutAccessoryView {
            selectedAnnotation = view.annotation as? MKPointAnnotation
            performSegueWithIdentifier("NextScene", sender: self)
        }
    }
    
  6. 实现一个将传递必要信息的prepareForSegue(可能是你想要传递注释,因此在第二个视图控制器中有一个annotation属性。)

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if let destination = segue.destinationViewController as? SecondViewController {
            destination.annotation = selectedAnnotation
        }
    }
    
  7. 现在您可以像以前一样创建注释:

    let annotation = MKPointAnnotation()
    annotation.coordinate = coordinate
    annotation.title = "Title1"
    annotation.subtitle = "Subtitle1"
    mapView.addAnnotation(annotation)
    
相关问题