2015-10-14 2 views
1

В Swift 1.2: Я хотел бы добавить кнопку в свои аннотации на карте. Первое нажатие на вывод показывает идентификатор пользователя, и это работает, но затем, нажав кнопку, я хочу отправить пользователя в контроллер подробного представления.Swift - добавление кнопки к моему MKPointAnnotation

вы можете иметь представление о том, что я ищу here и here

пытались применить эти решения, но я думаю, что я что-то не хватает. Это еще один пример того, что я ищу

enter image description here

это мой класс декларация:

import UIKit 
import MapKit 
import CoreLocation 
import Parse 

class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, UIActionSheetDelegate { 

и это часть коды, где я хотел бы создать аннотации с помощью кнопок :

// MARK: - Create Annotation 

    func createAnnotations(point: PFGeoPoint, address: String) 
    { 
     println("*** this evaluates n.3 ***") 
     var query = PFUser.query() 


     query?.whereKey("location", nearGeoPoint: point, withinKilometers: withinKms) 
     query?.orderByAscending("location") //MARK: Put list in order 

     //MARK: Not include current user on the map 
     var me = PFUser.currentUser()?.username 
     query?.whereKey("username", notEqualTo: me!) 

     query?.limit = self.kLimitNumberForQueryResults 


     query?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in 

      if error == nil 
      { 
       for(var i = 0; i < objects!.count; i++) { 

        let user = objects![i] as! PFUser 
        var myHomePin = MKPointAnnotation() 
        let userPoint = user["location"] as! PFGeoPoint 
        myHomePin.coordinate = CLLocationCoordinate2DMake(userPoint.latitude, userPoint.longitude) 
        myHomePin.title = user.username 

//MARK: core of the problem     
//     let detailButton : UIButton = UIButton.buttonWithType(UIButtonType.DetailDisclosure) as! UIButton 
//     myHomePin.rightCalloutAccessoryView = detailButton 
// 




//     myHomePin.subtitle = address 
        self.mapView.addAnnotation(myHomePin) 
        //     self.closeUsersArray.append(user.username!) //MARK: Test 

       } 






//     println("this is the array of users * \(self.closeUsersArray) *") //MARK: Test 
      } 
      else 
      { 
       println("Error: " + error!.localizedDescription) 
      } 

     }) 

    } 

благодарит заранее!

ответ

2

Используйте метод делегата «viewForAnnotation» для настройки левой и правой сторонних аксессуаров. а также UIButton.buttonWithType заменяется, это будет работать: редактирование: все методы делегата нужна, но я не сделал, хотя вашу функцию createAnnotation, потому что вы сказали, его работой тонкой

class MapViewController: UIViewController, MKMapViewDelegate // 
{ 
    @IBOutlet weak var mapView: MKMapView!{ //make sure this outlet is connected 
     didSet{ 
      mapView.delegate = self 
     } 
    } 

    // MARK: - Map view delegate 

    func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { 
     var view = mapView.dequeueReusableAnnotationViewWithIdentifier("AnnotationView Id") 
     if view == nil{ 
      view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "AnnotationView Id") 
      view!.canShowCallout = true 
     } else { 
      view!.annotation = annotation 
     } 

     view?.leftCalloutAccessoryView = nil 
     view?.rightCalloutAccessoryView = UIButton(type: UIButtonType.DetailDisclosure) 
     //swift 1.2 
     //view?.rightCalloutAccessoryView = UIButton.buttonWithType(UIButtonType.DetailDisclosure) as UIButton 

     return view 
    } 

    func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { 
     //I don't know how to convert this if condition to swift 1.2 but you can remove it since you don't have any other button in the annotation view 
     if (control as? UIButton)?.buttonType == UIButtonType.DetailDisclosure { 
       mapView.deselectAnnotation(view.annotation, animated: false) 
       performSegueWithIdentifier("you're segue Id to detail vc", sender: view) 
      } 
     } 
    } 

    //Your function to load the annotations in viewDidLoad 

} 
+0

Я попробовал, поставив вас FUNC выше моего «createAnnotations ", bu получил это: MapViewController.swift: 192: 51: Дополнительный аргумент 'type' при вызове – biggreentree

+0

Используете ли вы Swift1.2? этот код работает отлично на swift2.0 – Lukas

+0

да! извините, не звонил! – biggreentree

Смежные вопросы