Thanks to @stevesliva for pointing me to this SO answer . I converted it to Swift. This is what I got.
I create an NSCollectionView in the ViewController:
import Cocoa class ViewController: NSViewController { var titles = [String]() var collectionView: NSCollectionView? override func viewDidLoad() { super.viewDidLoad() self.titles = ["Banana", "Apple", "Strawberry", "Cherry", "Pear", "Pineapple", "Grape", "Melon"] collectionView = NSCollectionView(frame: self.view.frame) collectionView!.itemPrototype = CollectionViewItem() collectionView!.content = self.titles collectionView!.autoresizingMask = NSAutoresizingMaskOptions.ViewWidthSizable | NSAutoresizingMaskOptions.ViewMaxXMargin | NSAutoresizingMaskOptions.ViewMinYMargin | NSAutoresizingMaskOptions.ViewHeightSizable | NSAutoresizingMaskOptions.ViewMaxYMargin var index = 0 for title in titles { var item = self.collectionView!.itemAtIndex(index) as! CollectionViewItem item.getView().button?.title = self.titles[index] index++ } self.view.addSubview(collectionView!) } }
The created CollectionViewItem in the ViewController simply loads the view, where I myself create the view of the element.
import Cocoa class CollectionViewItem: NSCollectionViewItem { var itemView: ItemView? override func viewDidLoad() { super.viewDidLoad()
Presentation itself:
import Cocoa class ItemView: NSView { let buttonSize: NSSize = NSSize(width: 100, height: 20) let itemSize: NSSize = NSSize(width: 120, height: 40) let buttonOrigin: NSPoint = NSPoint(x: 10, y: 10) var button: NSButton? override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect)
To set the button title, I use the hack view. (for-loop in ViewController) If there is a better way to set a title, feel free to leave a comment.
source share