How to use array of objects as NSCollectionview Datasource in Xcode MacOS

Hiii. I’m new here and new to Swift and Xcode.

After some codes, I have an array of image views with this code:

 **var imageViews = [NSImageView]()**

and they are filled with images from a folder in my system. I want a way to use them in a collectionView as data source. Is it possible? And How?
I want a very very simple grid of them and I think collectionView is what I should use rather than gridView.

I want a simple and quick way to show the items. I cannot use a code like:
collectionView.dataSource = imageviews

because after an error, Xcode suggests to do this:
collectionView.dataSource = imageViews as? NSCollectionViewDataSource
and its not working.

I think you should take a look at this tutorial, since you are doing a Mac app:
https://www.raywenderlich.com/1246-collection-views-in-os-x-tutorial

A more recent iOS tutorial is here:
https://www.raywenderlich.com/9334-uicollectionview-tutorial-getting-started

You typically make the viewController the dataSource for the collection view, something like this:

extension ViewController : NSCollectionViewDataSource {

  func collectionView(collectionView: NSCollectionView, 
  numberOfItemsInSection section: Int) -> Int {
     // return number of items
  }
  
  func collectionView(collectionView: NSCollectionView, 
    itemForRepresentedObjectAtIndexPath indexPath: NSIndexPath) 
    -> NSCollectionViewItem {
       // return an NSCollectionViewItem for specified item
   }

}

It gets pretty elaborate, but that is because you have so much controller over how your data is displayed in the collection view.

1 Like

@sgerrard Thank you so much for answer. At last I could create a Collection View, with another little problem.

So now I have a class and XIB file. And like you said, now i have a code like “return item” for func 2 and its fine.

in xib file i have an Image View (with a default image) and a label. So my items have a default image and easily load in a grid and its ok now.

But now the problem is I dont know how to say the items, to load my array images. I used somthing like:

    item.imageView.image = imageviews[i].image
    return item

with no error but not working. I even tried it in xib file loader and again nothing. Even 1 of them.
And what if I want o use a button to load items? In this way items will load at loading time, but I want to load them with click of a button.

This topic was automatically closed after 166 days. New replies are no longer allowed.