【发布时间】:2020-06-03 18:00:48
【问题描述】:
目前,我有一个在地图上显示位置的地图视图。当在地图上选择位置注释时,它会打开一个新的视图控制器。如何将地图注释中显示的地点名称传递给新的视图控制器?
这是 mapView 的代码。
import UIKit
import MapKit
struct PlacesOnMap {
var name: String
var latitude: Double
var longitude: Double
init(name: String, latitude: Double, longitude: Double) {
self.name = name
self.latitude = latitude
self.longitude = longitude
}
}
class MapViewController: UIViewController {
@IBOutlet var mapView: MKMapView!
var places = [PlacesOnMap(name: place 1),
PlacesOnMap(name: place 2)
]
override func viewDidLoad() {
super.viewDidLoad()
setupAnnotations()
}
func setupAnnotations() {
let places = places.map { placeOnMap -> MKPointAnnotation in
let place = MKPointAnnotation()
place.coordinate = CLLocationCoordinate2D(latitude: placeOnMap.latitude, longitude: placeOnMap.longitude)
place.title = placeOnMap.name
return place
}
mapView.addAnnotations(places)
}
extension MapViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
guard let annotationTitle = view.annotation?.title else { return }
let storyboard: UIStoryboard = UIStoryboard(name: "MyCommunityStoryboard", bundle: nil)
let destVC = storyboard.instantiateViewController(withIdentifier: "DetailMapItemsViewController") as! DetailMapItemsViewController
destVC.placeNameText = annotationTitle!
navigationController?.pushViewController(destVC, animated: true)
}
}
这是迄今为止我的 DetailViewController 的内容。
import UIKit
struct PlacesDetailView {
var name: String
init(name: String) {
self.name = name
}
class DetailMapItemsViewController: UIViewController {
@IBOutlet weak var nameOfPlaceLabel: UILabel!
var placeNameText: String = ""
override func viewDidLoad() {
super.viewDidLoad()
nameOfPlaceLabel?.text = placeNameText
}
}
【问题讨论】: