簡體   English   中英

如何將特定元素從數組傳遞到另一個視圖或 function? Swift

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

我正在從服務器加載數據並將其傳遞給數組。 該數據包括坐標、文本、圖像等。它還包含名為“id”的變量(我考慮過為特定 id 排序數組,但不確定這是否是一個好的解決方案)。 此數據用於顯示 map 上的標記。 我的任務是在單獨的視圖中顯示此標記的詳細信息。 如何告訴此詳細信息屏幕選擇了哪個標記或如何根據所選標記從數組中獲取特定元素?

這是我創建標記:

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
    }

您可以使用 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
}

希望這會有所幫助!

這是一個非常籠統的問題,在 Swift / Cocoa 中的對象之間有很多方法可以傳遞數據,例如 segues、delegate、notifications、singleton 模式:或者只是直接使用依賴項初始化或不使用它

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM