我正在尝试在El Capitan中引入的新的NSCollectionView
API。
在WWDC视频之后,我创建了NSCollectionViewFlowLayout
的子类来确定集合 View 的布局。
class Layout : NSCollectionViewFlowLayout {
override func prepareLayout() {
super.prepareLayout()
self.minimumInteritemSpacing = 0
self.minimumLineSpacing = 0
let cheight = self.collectionView!.bounds.height
let cwidth = self.collectionView!.bounds.width
self.itemSize = CGSizeMake(cwidth / 2.0, cheight / 6.0)
}
}
之后,我创建了一个
NSObject
子类作为数据源。class DataSource : NSObject, NSCollectionViewDataSource {
func collectionView(collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(collectionView: NSCollectionView, itemForRepresentedObjectAtIndexPath indexPath: NSIndexPath) -> NSCollectionViewItem {
/* DOESN'T GET CALLED! */
let item = collectionView.makeItemWithIdentifier("cell", forIndexPath: indexPath)
item.view.wantsLayer = true
item.view.layer?.backgroundColor = NSColor.redColor().CGColor
return item
}
}
问题是从未调用
collectionView:itemForRepresentedObjectAtIndexPath:
。这是初始化集合 View 的方式:
let collectionView = NSCollectionView(frame: view.bounds)
let dataSource = DataSource()
let layout = Layout()
collectionView.collectionViewLayout = layout
collectionView.registerClass(NSCollectionViewItem.self,
forItemWithIdentifier: "cell")
collectionView.dataSource = dataSource
collectionView.backgroundColors = [.blackColor()]
我可以在其 super View 中清楚地看到集合 View ,但是没有单元格。
另外,如果在委托(delegate)外部(但是在单元类注册之后)调用了此行,则会使应用程序崩溃!
let item = collectionView.makeItemWithIdentifier("cell", forIndexPath: /*any index path*/)
我是在做错什么,还是
NSCollectionView
新API被破坏了?谢谢。
最佳答案
方法makeItemWithIdentifier是至关重要的,它在 bundle 包中查找名为“cell”的.xib:如果来自另一个 bundle 包,则可能需要使用registerNib:forItemWithIdentifier:进行注册。
因此,您的问题就在此之前,因为您的collectionView:itemForRepresentedObjectAtIndexPath永远不会被调用,而这可能是由您的模式引起的:为什么您创建一个新类来充当数据源,而不使用NSCollectionView所在的NSViewController?
我一直这样做,并且使用新的API都可以完美地工作。希望这可以对您有所帮助!