当用户点击自定义信息窗口时,我正试图将谷歌地图的userData
传递到下一个视图。
首先我创建了这样的模型对象。
import UIKit
import Firebase
struct Team {
var key: String
var teamName: String
var league: String
var lat: Double
var lng: Double
init(snapshot: DataSnapshot) {
self.key = snapshot.key
self.teamName = (snapshot.value as! NSDictionary)["teamName"] as? String
self.league = (snapshot.value as! NSDictionary)["league"] as? String ?? ""
self.lat = (snapshot.value as! NSDictionary)["lat"] as? Double ?? 0
self.lng = (snapshot.value as! NSDictionary)["lng"] as? Double ?? 0
}
}
我获取数据库并将userData
添加为
var teams = [Team?]()
func fetchTeams(){
let teamRef = Database.database().reference().child("teams")
teamRef.observe(.value, with: { (snapshot) in
var result = [Team]()
for child in snapshot.children {
let child = Team(snapshot: child as! DataSnapshot)
result.append(child)
self.teams = result
}
for team in self.teams {
guard let lat = team?.lat else { return }
guard let lng = team?.lng else { return }
let marker: GMSMarker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(lat, lng)
marker.map = self.mapView
marker.userData = team
}
}, withCancel: nil)
}
此func
完美无缺,因此我猜userData
的属性正确无误。
func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
let infoWindow = Bundle.main.loadNibNamed("Marker", owner: self, options: nil)?.first as! MarkerView
infoWindow.teamLabel.text = (marker.userData as! Team).teamName
return infoWindow
}
func mapView(_ mapView: GMSMapView, didTapInfoWindowOf marker: GMSMarker) {
self.performSegue(withIdentifier: cellId, sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == cellId {
let next: NextViewController = segue.destination as! NextViewController
let marker = GMSMarker()
next.team = marker.userData as? Team
}
}
我实现了如上所述将数据传递给NextViewController
。
它工作正常,直到performSegue
,但next.team
为零。有谁知道为什么?
提前谢谢!
答案 0 :(得分:1)
您遇到此问题是因为您正在创建一个空的GMSMarker
,当然这个空的GMSMarker
没有任何userData,您必须将选定的GMSMarker
作为参数传递给performSegue
,特别是sender
参数,并投放为Team
并将其传递给您的NextViewController
func mapView(_ mapView: GMSMapView, didTapInfoWindowOf marker: GMSMarker) {
self.performSegue(withIdentifier: cellId, sender: marker.userData)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == cellId {
let next: NextViewController = segue.destination as! NextViewController
if let teamData = sender as? Team{
next.team = teamData
debugPrint("teamData is fine")
}
debugPrint("segue identifier is correct")
}
}