2015-10-16 136 views
-1

當我嘗試在註釋中添加按鈕時出現問題。將按鈕添加到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。

希望有人能幫助我:)

在此先感謝!

+0

的[?我如何添加一個按鈕來MKPointAnnotation](可能的複製http://stackoverflow.com/questions/28225296/how-can-i-add-a-button-to-mkpointannotation) – vikingosegundo

回答

3

,在你的第一個環節回答基本上是正確的,但它需要斯威夫特被更新2.

底線,在回答你的問題,當您創建註釋你不添加按鈕。當您在viewForAnnotation中創建註釋視圖時,您可以創建該按鈕。

所以,你應該:

  1. 設置視圖控制器是地圖視圖的委託。

  2. 使視圖控制器符合地圖視圖代表協議,例如:

    class ViewController: UIViewController, MKMapViewDelegate { ... } 
    
  3. 通過控制從拖動添加從視圖控制器(未按鈕)到下一個場景一SEGUE與地圖視圖到下一場景的場景以上視圖控制器圖標:

    enter image description here

    然後選擇賽格瑞然後給這故事板標識符(「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) 
    
+0

非常感謝Rob,我不明白我在創建註釋時不添加按鈕的原則。現在它對我來說更加清晰! – Mick