简体   繁体   中英

How to pass specific element from array to another view or function? Swift

I'm loading data from server and passing it to an array. This data includes coordinates, text, images etc. Also it contains variable, named "id" (I thought about sorting array for specific id, but not sure if this is a good solution). This data is used to show markers on map. My task is to show this marker's details on separate view. How to tell this details screen which marker was chosen or how to get specific element from array based on chosen marker?

This is were I create markers:

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
    }

You can use GMS delegate method to check which marker is tapped.

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
}

Hope this will help!

This is a pretty generic question, and there are a lot of ways of passing data between objects in Swift / Cocoa, eg segues, delegates, notifications, singleton pattern, or simply just direct initialization with dependency injection or without it:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM