簡體   English   中英

選擇collectionView單元格時如何獲取項目ID

[英]how to get item id when collectionView cell is selected

I just want to pass the item id to the next view controller when the item of collectionView is selected.

在這里我存儲從 API 獲得的數據

這是一些代碼-->

var posts = [[String: Any]]()
func apicall() {
        let Url = String(format: "http:example.com")
        guard let serviceUrl = URL(string: Url) else { return }
        
        var request = URLRequest(url: serviceUrl)
        request.httpMethod = "POST"
        request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
        
        
        let session = URLSession.shared
        session.dataTask(with: request) { (data, response, error) in
            if let response = response {
                print(response)
            }
            if let data = data {
                do {
                    if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]{
                        
                        self.posts = (json["data"] as? [[String : Any]])!
                        
                        DispatchQueue.main.async() {
                            self.collectionView.reloadData()
                        }
                    }
                } catch {
                    print(error)
                }
            }
            }.resume()
    }

現在我得到了數據,我想傳遞只選擇的那個項目的項目 ID

 @IBAction func onClickNext(_ sender: Any) {
        let controller = self.storyboard?.instantiateViewController(withIdentifier: "secondViewController") as! secondViewController
        self.navigationController?.pushViewController(controller, animated: true)
       
    }

這里是 didSelectItemAt 索引路徑的代碼

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as! secondCollectionViewCell
}

始終從數據源數組model獲取數據,從不從視圖中獲取

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let item = self.posts[indexPath.item]
        let id = item["id"]
        // do things with id
}

那時,如果您啟用了選擇,則集合視圖將能夠為您返回集合視圖中所有選定單元格的IndexPath 請查看UICollectionView上的此屬性

var indexPathsForSelectedItems: [IndexPath]? { get }

indexPathForSelectedItems 的蘋果文檔

然后在您的@IBAction func中執行此操作

@IBAction func onClickNext(_ sender: Any) {
  // logic to grab the id from self.posts using the selected indexPaths ie.
  let selectedItems = self.collectionView.indexPathsForSelectedItems ?? []
  let ids = selectedItems.compactMap { self.posts[$0.row] }

  let controller = self.storyboard?.instantiateViewController(withIdentifier: 
           "secondViewController") as! secondViewController
  controller.selectedIds = ids // all the selected ids
  
  self.navigationController?.pushViewController(controller, animated: true)
}

所以你應該這樣做,我不知道數據結構在你的self.posts屬性中的樣子,但上面的代碼給了你一個想法。 為了簡化這一點,請嘗試在操場上運行以下代碼並查看結果。

import UIKit

let posts: [String] = ["Carrot_Post", "Pencil_Post", "Dish_Post", "Data_Post",
                       "iOS_Post", "Kitties_Post", "VideoGamesPost", "Bitcoin_Post"]
let selected: [Int] = [1, 3, 0, 5]

let items: [String] = selected.compactMap({ posts[$0] })

print(items) // output: ["Pencil_Post", "Data_Post", "Carrot_Post", "Kitties_Post"]

希望對您的問題有所幫助。

暫無
暫無

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

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