简体   繁体   中英

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.

here I store the data that I get from API

here's some code -->

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()
    }

now I get the data and I want to pass the item id of that item which is selected only

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

here the code of the didSelectItemAt index path

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

Always get the data from the model , the data source array, never from the view

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

Well at that moment if you have the selection enabled the collection view will be able to return to you the IndexPath for all selected cells in the collection view. Please take a look to this property on the UICollectionView

var indexPathsForSelectedItems: [IndexPath]? { get }

apple documentation for indexPathForSelectedItems

then at your @IBAction func just do this

@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)
}

so something like that you should do, i have no idea how the data structure looks like inside your self.posts property but the above code gives you an idea. To simplify this try to run below code in a playground and see the result.

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"]

Hope that helps with your problem.

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