我有一个视图控制器,它允许用户将坐标输入到文本字段中,并将这些坐标(以及标题)更新到一个数组中。在我的 MapView VC 中,我希望能够根据用户输入的内容放置引脚。但是,当我运行代码时,不会读取输入坐标,也不会在 MapView 上放置任何内容。我有一种预感,要么我没有正确保存这些位置,要么我的引脚放置不起作用,但我不确定错误可能出在哪里。
输入坐标:
import UIKit
import CoreLocation
// here I initialize my array locations
var locations: [Dictionary<String, Any>] = []
class OtherVC: UIViewController {
@IBOutlet weak var latitudeField: UITextField!
@IBOutlet weak var longitudeField: UITextField!
@IBOutlet weak var titleTextField: UITextField!
var coordinates = [CLLocationCoordinate2D]()
override func viewDidLoad() {
super.viewDidLoad()
}
// this IBOutlet takes the input from the textfield
@IBAction func addToMap(_ sender: Any) {
let lat = latitudeField.text!
let long = longitudeField.text!
let title = titleTextField.text!
let location: [String: Any] = ["title": title, "latitude": lat, "longitude": long]
locations.append(location)
}
下面是我的 MapView 的代码:
import UIKit
import MapKit
class MapViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
//iterates each location in my array to pull the title and coordinate
for location in locations {
let annotation = MKPointAnnotation()
annotation.title = location["title"] as? String
annotation.coordinate = CLLocationCoordinate2D(latitude: location["latitude"] as! Double, longitude: location["longitude"] as! Double)
mapView.addAnnotation(annotation)
}
}
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
}
}
}