【发布时间】:2017-01-17 04:23:22
【问题描述】:
我的这个应用程序的意图是允许用户在选项卡控制器的一个选项卡中输入任何一组坐标,而在另一个选项卡中,坐标将被放置在带有注释的 pin 中。
我一直在尝试实现的方法是使用一个全局数组,该数组附加输入坐标并在另一个类文件(使用 mapView)中调用。我在尝试遍历数组以放置引脚时遇到了很多问题,我不确定出了什么问题。
输入信息类文件:
import UIKit
import CoreLocation
var locations: [Dictionary<String, Any>] = [] // here I initialize my array
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 coordinate input information from the user
@IBAction func addToMap(_ sender: Any) {
let lat = latitudeField.text!
let long = longitudeField.text!
let title = titleTextField.text!
var location: [String: Any] = ["title": title, "latitude": lat, "longitude": long]
locations.append(location) // adding the info to the array
let mapVC : MapViewController = MapViewController()
mapVC.iterateLocations()
}
}
MapView 类文件:
import UIKit
import MapKit
class MapViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
}
// this method here iterates through each of the locations in the array
func iterateLocations() -> Bool {
for location in locations {
var momentaryLat = (location["latitude"] as! NSString).doubleValue
var momentaryLong = (location["longitude"] as! NSString).doubleValue
let annotation = MKPointAnnotation()
annotation.title = location["title"] as? String
annotation.coordinate = CLLocationCoordinate2D(latitude: momentaryLat as CLLocationDegrees, longitude: momentaryLong as CLLocationDegrees)
mapView.addAnnotation(annotation)
}
return true
}
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
}
}
“mapView.addAnnotation(annotation)”行中弹出错误,表示在尝试打开 Optional 时发现了一个 nil。所以我认为错误是信息没有保存在注释中,但我没有立即看到这是错误的。
欢迎任何可能更容易实现的方法的替代方法!
【问题讨论】:
标签: arrays swift mkmapview coordinates