如何将特定元素从数组传递到另一个视图或函数? Swift
How to pass specific element from array to another view or function? Swift
我正在从服务器加载数据并将其传递给数组。此数据包括坐标、文本、图像等。它还包含名为 "id" 的变量(我考虑过为特定 id 排序数组,但不确定这是否是一个好的解决方案)。此数据用于在地图上显示标记。
我的任务是在单独的视图中显示此标记的详细信息。如何告诉此详细信息屏幕选择了哪个标记或如何根据所选标记从数组中获取特定元素?
这是我创建的标记:
for element in spots {
let image = UIImage(named: element.type)
let position = CLLocationCoordinate2D(latitude: element.coordinates.latitude, longitude:
element.coordinates.longitude)
marker = GMSMarker(position: position)
marker.icon = image
marker.map = mapView
}
这是一个非常笼统的问题,在 Swift / Cocoa 中有很多对象之间传递数据的方法,例如segues, delegates, notifications, singleton pattern, 或者只是简单地使用或不使用依赖注入直接初始化:
let separateView = SeparateView()
separateView.marker = marker // Note that you need a var defined in your separate view in order to set it sooner, marker is your marker defined from before
navigationController?.pushViewController(separateView, animated: true)
您可以使用 GMS 委托方法来检查点击了哪个标记。
for element in spots {
let image = UIImage(named: element.type)
let position = CLLocationCoordinate2D(latitude: element.coordinates.latitude, longitude:
element.coordinates.longitude)
marker = GMSMarker(position: position)
marker.icon = image
marker.map = mapView
// add the element info to marker userData property
marker.userData = element
}
// function to check if which icon tapped
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
// get the element info from marker
let element = marker.userData
//code to navigate to detail view
}
希望对您有所帮助!
我正在从服务器加载数据并将其传递给数组。此数据包括坐标、文本、图像等。它还包含名为 "id" 的变量(我考虑过为特定 id 排序数组,但不确定这是否是一个好的解决方案)。此数据用于在地图上显示标记。 我的任务是在单独的视图中显示此标记的详细信息。如何告诉此详细信息屏幕选择了哪个标记或如何根据所选标记从数组中获取特定元素?
这是我创建的标记:
for element in spots {
let image = UIImage(named: element.type)
let position = CLLocationCoordinate2D(latitude: element.coordinates.latitude, longitude:
element.coordinates.longitude)
marker = GMSMarker(position: position)
marker.icon = image
marker.map = mapView
}
这是一个非常笼统的问题,在 Swift / Cocoa 中有很多对象之间传递数据的方法,例如segues, delegates, notifications, singleton pattern, 或者只是简单地使用或不使用依赖注入直接初始化:
let separateView = SeparateView()
separateView.marker = marker // Note that you need a var defined in your separate view in order to set it sooner, marker is your marker defined from before
navigationController?.pushViewController(separateView, animated: true)
您可以使用 GMS 委托方法来检查点击了哪个标记。
for element in spots {
let image = UIImage(named: element.type)
let position = CLLocationCoordinate2D(latitude: element.coordinates.latitude, longitude:
element.coordinates.longitude)
marker = GMSMarker(position: position)
marker.icon = image
marker.map = mapView
// add the element info to marker userData property
marker.userData = element
}
// function to check if which icon tapped
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
// get the element info from marker
let element = marker.userData
//code to navigate to detail view
}
希望对您有所帮助!