0

What is the correct way to pass data from my ViewController to my CollectionViewItem?

ViewContoller

    func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {        
        let item = CollectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "CollectionViewItem"), for: indexPath) as! CollectionViewItem
        item.themeName = getDirectoryContentByIndex(index: indexPath)
        return item
    }

CollectionViewItem

class CollectionViewItem: NSCollectionViewItem {


   var themeName: String!
   @IBOutlet weak var NameOfTheme: NSTextFieldCell!

   override func viewDidLoad() {
      super.viewDidLoad()
      // Do view setup here.
   }
}

Edit: I want to assign the themeNameas stringValue of NameOfTheme. But if I set the value, the IBOutlet is nil.

  • One way is to use Protocols and Delegates. Protocols and Delegates are used to talk from one class to another. You can learn how to use that here: https://stackoverflow.com/questions/40501780/examples-of-delegates-in-swift – Erik Batista Nov 03 '17 at 12:22

1 Answers1

0

I recommend you to make fields of your cell private and make configure(YOUR_PARAMS) (in our case configure(themeName: String). So in cellForRow you will call this function cell.configure(themeName: "")

Mikhail Maslo
  • 616
  • 6
  • 13
  • Good idea. But it does not work for me. The problem is my `@IBOutlet weak var NameOfTheme: NSTextFieldCell!` is not set at the moment of pass the data. So i cant set the stringValue :( – Kenny Wagenknecht Nov 03 '17 at 13:30
  • @KennyWagenknecht I've never used `NSCollectionView`, but I think it's very similar to `UICollectionView`. You need to register cell type in correct way (here you are using xib file probably) - just google it. Make sure you associated file with `CollectionViewItem` right - again google will help you with those basic things. Then you can use it in the method above. Make breakpoints on awakeFromNib and other life cycle methods to be sure you're doing connections right – Mikhail Maslo Nov 03 '17 at 17:09