Search code examples
iosswiftcollectionview

swift ios how to access data from a collection view


I have code below in a collection view and its result, what I want to know is how to access those data from my collection view to my function prepare. I want to get the value of getTempDetails like

getTempDetails["name"] as! String 

to be the value of my

destination.chore_name = getTempDetails["name"] as! String

but I can't seem to access it. thanks

code for prepare

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let distanation = segue.destination as? ChoreDetailsViewController {
            distanation.chore_name  = "Hi"
        }
    }

code for

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // handle tap events
//        print("You selected cell #\(indexPath.item)!")
//        print("emong gepili:" , titleArray[indexPath.row])

        if indexPath.row == 0 {
            performSegue(withIdentifier: "goToSegue", sender: nil)
        } else {
              performSegue(withIdentifier: "gotoDetails", sender: nil)
            print("You selected cell #\(indexPath.item)!")
            if let getTempDetails: [String : Any] = getAllDetail[indexPath.row] {
                print("You selected ID #\( getTempDetails["reward"] as? String  ?? "" )!")
                print("You selected ID #\( getTempDetails["desc"] as? String  ?? "" )!")
                print("You selected ID #\( getTempDetails["sched"] as? String  ?? "" )!")

Solution

  • use the keyword of indexPathsForSelectedItems for colletionview

       override func prepare(for segue: UIStoryboardSegue, sender: Any?) 
    {
          if segue.identifier == "gotoDetails" , 
           let nextScene = segue.destination as? ChoreDetailsViewController , 
           let indexPath = self.yourCollectionViewName. indexPathsForSelectedItems().first  {
            if let getTempDetails: [String : Any] = getAllDetail[indexPath.item] {
                    print("You selected ID #\( getTempDetails["reward"] as? String  ?? "" )!")
                    print("You selected ID #\( getTempDetails["desc"] as? String  ?? "" )!")
                    print("You selected ID #\( getTempDetails["sched"] as? String  ?? "" )!")
    
         nextScene.chore_name = getTempDetails["name"] as! String
        }
       }
       }