Sean
Sean

Reputation: 2529

Unable to assign value to NSCollectionView objects from delegate in Mac OSX / Swift

My Mac OSX NSViewController is acting unexpectedly. I've done UICollectionViews on iOS dev, but stumped with this.

I have created a CollectionView Item class that handles the class that has outlets to NSImage and NSLabel:

import Cocoa

class CollectionViewItem: NSCollectionViewItem {

@IBOutlet weak var messageThumb: NSImageView!
@IBOutlet weak var dateLabel: NSTextField!


    override func viewDidLoad() {
        super.viewDidLoad()
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.lightGray.cgColor
        view.layer?.borderColor = NSColor.white.cgColor
        view.layer?.borderWidth = 0.0
    }

}

The delegate is listed below and is triggered, and the number of items is correct - so I know the delegates and sources are right. It correctly pulls the Item View (I believe - though, it says "object (null)") from running "po item" in debuging in console

<Konch.CollectionViewItem: 0x6000001232a0>{represented object: (null),
view: <NSView: 0x600000123200> (frame {{0, 0.5}, {65, 87}}), selected:
NO}

but the related NSImage and NSLabel always come up as nil and I can't assign values to it....

extension RecordViewController: NSCollectionViewDataSource {

    func numberOfSections(in collectionView: NSCollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.messages.count
    }

    func collectionView(_ itemForRepresentedObjectAtcollectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {

        let item = collectionView.makeItem(withIdentifier: "CollectionViewItem", for: indexPath) as! CollectionViewItem
        let message = self.messages[indexPath.item]

        guard let collectionViewItem = item as? CollectionViewItem else {return item}

        collectionViewItem.dateLabel.stringValue = "SADFDF"

        return item
    }

}

Am I mis-understanding something?

UPDATE: Here is my xib xib file

And IB outlets on CollectionView VC

enter image description here

UPDATE:

Answering @El Tomato, I am naming the related class in the Xib

enter image description here

Upvotes: 2

Views: 443

Answers (1)

Sean
Sean

Reputation: 2529

Got it working, but still don't fully understand why.

I suppose in Mac OS development you do not need to create outlets from your objects to the class. Instead I connected my outlets to the "Objects" -> "Collection View Item" as shown below.

enter image description here

For some reason, without any IBOutlet references, I could set my image view and label from within the class as shown here.

enter image description here

Never needed to register the xib or anything.

Still confused how the whole system is working together.

Upvotes: 2

Related Questions