2016-12-23 3 views
4

입력했을 때 을 다른 탭의지도에 배치하는 위도와 경도 좌표의 사용자 입력을받을 수있는지도 앱을 만들려고합니다. My FirstVC는 사용자가 좌표를 입력 할 수있는 OtherVC에 이어지는 "Add Locations"버튼으로 구성됩니다. SecondVC는 MapView로 구성됩니다. 내 생각은 특정 좌표 배열을 갖는 것이고 새로운 좌표가이 배열에 추가됩니다. 이 배열을 MapView로 전송하는 방법을 모르기 때문에 실행이 부족합니다.Swift MKMapViewDelegate -보기 컨트롤러 간의 좌표 전송

import UIKit 
import CoreLocation 

class OtherVC: UIViewController { 

@IBOutlet weak var latitudeField: UITextField! 
@IBOutlet weak var longitudeField: UITextField! 

var coordinates = [CLLocationCoordinate2D]() 

override func viewDidLoad() { 
    super.viewDidLoad() 

} 


@IBAction func addToMap(_ sender: Any) { 
    let lat = Double(latitudeField.text!) 
    let long = Double(longitudeField.text!) 

    self.coordinates.append(CLLocationCoordinate2D(latitude: lat!, longitude: long!)) 
} 




} 

맵뷰 MapView의 경우 :

import UIKit 
import MapKit 
class MapViewController: UIViewController, MKMapViewDelegate { 
@IBOutlet weak var mapView: MKMapView! 



var coordinates = [CLLocationCoordinate2D]() { 
    didSet { 
     // Update the pins 
     // Since it doesn't check for which coordinates are new, it you go back to 
     // the first view controller and add more coordinates, the old coordinates 
     // will get a duplicate set of pins 
     for (index, coordinate) in self.coordinates.enumerated() { 
      let annotation = MKPointAnnotation() 
      annotation.coordinate = coordinate 
      annotation.title = "Location \(index)" 

      mapView.addAnnotation(annotation) 
     } 
    } 
} 

override func viewDidLoad() { 
    super.viewDidLoad() 
    mapView.delegate = self 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { 
    let identifier = "pinAnnotation" 
    var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView 

    if annotationView == nil { 
     annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) 
     annotationView?.canShowCallout = true 
    } 

    annotationView?.annotation = annotation 
    return annotationView 
} 
} 

enter image description here

답변

2

나는 당신이 두 번째의 ViewController를 얻을 수있다 필요가 있다고 생각 좌표의 입력의

: 여기에 지금까지 무엇을 가지고 MapViewController tabBarController에서 가져온 다음 좌표 배열을 전달합니다. 따라서 addToMap 액션에서 this로 바꿉니다.

@IBAction func addToMap(_ sender: Any) { 
     let lat = Double(latitudeField.text!) 
     let long = Double(longitudeField.text!) 

     self.coordinates.append(CLLocationCoordinate2D(latitude: lat!, longitude: long!)) 
     //here we pass the coordinate array to mapViewController 
     if let mapViewController = self.tabBarController?.viewControllers?[1] as? MapViewController 
     { 
      mapViewController.coordinates = self.coordinates 
     } 
    } 

당신은 그림에서와 같이, 네비게이션 컨트롤러를 추가도 필요 enter image description here

나는 이것이 일반적으로 난 단지 직접 하나의 ViewController에서 데이터를 전달하는 방법을 사용 말하는 당신에게

+0

if-let 문에 break 문을 추가 했으므로 실행되고 좌표가 전송됩니다. 그러나 mapViewController 좌표를 수신 할 때 "mapView.addAnnotation (annotation)"오류가 발생합니다. 문제가 무엇인지 잘 모르겠습니다. – Kevin

+0

오류를 게시 할 수 있습니까?, CLLocation2D가 유효한지 확인해야하는 플로트 번호가 아니라는 것을 기억하십시오. 원하는 경우 내 대답을 향상시킬 수 있습니다. –

+0

"스레드 1 : EXC_BAD_INSTRUCTION"오류가 발생했습니다. 관련 될 수 있습니까? ClLocation2D의 수치 형 – Kevin

1

도움이되기를 바랍니다 다음에 부모 자식 관계가있는 경우 prepareForSegue 또는 in 및 unwind (자식에서 부모로)에서 수행 할 수 있습니다. 그렇지 않으면 게시자 구독자 모델을 알림과 함께 사용하는 것이 더 좋습니다. 당신의 변경 사항을 조정하면 당신은 통지를 게시 :

NotificationCenter.default.post(name: NSNotification.Name("MapViewController.coordinate.updated"), object: self, userInfo: nil) 
변경 MapViewController의 좌표에 대한 관심

이제 누구든지들을 수 있습니다 :

override func viewDidLoad() { 
    super.viewDidLoad() 
    NotificationCenter.default.addObserver(self, selector: #selector(coordinateUpdated), name: NSNotification.Name("coordinate.updated"), object: nil) 
} 

deinit { 
    NotificationCenter.default.removeObserver(self) 
} 

@objc private func coordinateUpdated(notification: Notification) { 
    if let source = notification.object as? MapViewController { 
     print(source.coordinates) 
    } 
} 

이의 의견은 느슨하게 결합하게하고 MapViewController 누가 걱정 할 필요가 없습니다 업데이트해야합니다. 가입자는 자신을 등록 할 책임이 있습니다.

관련 문제