1

I have a collection view and Json array. I Want to get specific data on another view by tapping collection view cell. I used to get data by using tags on buttons on main view, but when I changed view with collection view, now theres no separate buttons, so collection view now works with indexes. How to do kind of parser to get data with tapped index from collection view?

import Foundation

class CardGenerator {
    static func generateCards(onMode mode: Letter) -> JsonEnum {

        let filepath = Bundle.main.path(forResource: "Data", ofType: "json")!
        let data = NSData(contentsOfFile: filepath)!
        let json = try! JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.allowFragments) as! [String: AnyObject]
        print(json)
        print(json  as? NSObject )
        let cards: JsonEnum = JsonEnum(img: "", txt: "", lett: "", sound: "")
        if let jsonCards = json[mode.rawValue] as? [String: AnyObject] {
            //for aso in jsonCards {
            print(jsonCards)

            let card = JsonEnum()
            if let image = jsonCards["image"] as? String {
                card.image = image
            }

            if let text =  jsonCards["text"] as? String {
                card.text = text
            }

            if let letter = jsonCards["letter"] as? String {
                card.letter = letter
            }

            if let sound = jsonCards["sound"] as? String {
                card.sound = sound
            }

            print(card.image, card.text, card.letter, card.sound)
            return card
        }
        return cards
    }
}
Ahmad F
  • 30,560
  • 17
  • 97
  • 143
SunCode
  • 43
  • 10

1 Answers1

0

The below UICollectionViewDelegate gets called when you select the UICollectionViewCell

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)

To use the data of specific cell tabbed, use the below code:-

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
            let cell = collectionView.cellForItem(at: indexPath)
           //here get data from cell
        }
Annie Gupta
  • 2,786
  • 15
  • 23
  • how to get data in this func using json? – SunCode Nov 04 '16 at 18:35
  • What you need to do is in `viewDidLoad` call your `generateCards` method and get the output in a variable and then in collectionView's `didSelectItemAt ` method get the value at index of output variable from `generateCards` using `indexPath.row` – Annie Gupta Nov 04 '16 at 18:43