【问题标题】:Add button to MKPointAnnotation将按钮添加到 MKPointAnnotation
【发布时间】:2015-10-16 15:11:49
【问题描述】:

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

在我提出这个问题之前,我已经在以下页面上搜索了答案: 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。

希望有人可以帮助我:)

提前致谢!

【问题讨论】:

标签: swift mkpointannotation


【解决方案1】:

您的第一个链接中的答案基本上是正确的,尽管它需要针对 Swift 2 进行更新。

底线,在回答您的问题时,您在创建注释时不添加按钮。当您在viewForAnnotation 中创建其注释视图时,您将创建该按钮。

所以,你应该:

  1. 将视图控制器设置为地图视图的代理。

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

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

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

  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)
    

【讨论】:

  • 非常感谢 Rob,我不明白创建注释时不添加按钮的原理。现在对我来说更清楚了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-29
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多