Search code examples
cocoacocoa-bindingsnscollectionviewkvcnscollectionviewitem

NSCollectionView does show nothing


I've tried to follow this guide:

Quick Start for Collection Views

using an NSImageView in the Collection View Item.

Nothing shows up, neither if i set the image with a Image Well neither if i set the array via code.

So i tried to do it programmatically, using

func representedObject(representedObject: AnyObject)
{
    super.representedObject = representedObject
    photoImageView.image = (representedObject as! NSImage)
    println("\(representedObject)")
}

in the Collection View Item (subclassed).

If I don't subclass Collection View Item Xcode tells me that there is no prototype set, if i subclass it it tells that "could not load the nibName"... (it's in the storyboard with correct identity set)

I can't have this Collection View to work :-(

Anyway, i like the bindings... so i'd like to achieve the correct result with bindings.. I checked and rechecked every passage in the document at the link and everything seems fine. the main difference is that the document uses the app delegate, i'm using a view controller.

i translated KVC methods in swift, i think they are correct since i know them have been called. Here them are:

func insertObject(p: ClientPhoto, inClientPhotoArrayAtIndex index: Int) {
    images.insertObject(p, atIndex: index)
}

func removeObjectFromClientPhotoArrayAtIndex(index: Int) {
    images.removeObjectAtIndex(index)
}

func setClientPhotoArray(a: NSMutableArray) {
    images = a
}

func clientPhotoArray() -> NSArray {
    return images
}

Solution

  • Their are basically 2 ways to work with NSCollectionView. 1 is to set the itemPrototype property and the other is to override newItemForRepresentedObject. The override method is more flexible and has the advantage that you using the technique below you can create the nscollectionviewitem in storyboard and all the outlets will be set correctly. Here is an example of how I use it:

    class TagsCollectionView: NSCollectionView {
    // ...
    override func newItemForRepresentedObject(object: AnyObject!) -> NSCollectionViewItem! {
        let viewItem = MainStoryboard.instantiateControllerWithIdentifier("tagCollectionViewItem") as! TagCollectionViewItem
        viewItem.representedObject = object
    
        return viewItem
    }