我正在试验新的NSCollectionViewAPI,它是在El Capitan中引入的。
在WWDC视频之后,我创建了一个NSCollectionViewFlowLayout子类来确定集合视图的布局。
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:从未被调用过。
我就是这样初始化集合视图的:
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()]我可以清楚地看到它的superview中的集合视图,但是没有单元格。
另外,如果在委托之外调用这一行(但是在注册了单元格类之后),则应用程序会崩溃!
let item = collectionView.makeItemWithIdentifier("cell", forIndexPath: /*any index path*/)我是做错什么了还是NSCollectionView新API坏了?
谢谢。
发布于 2016-02-25 09:04:39
方法makeItemWithIdentifier是关键的,在包中查找名为"cell“的.xib :您可能需要将它注册到registerNib:forItemWithIdentifier:如果它来自另一个包。
因此,您的问题在此之前就出现了,因为您的collectionView:itemForRepresentedObjectAtIndexPath从未被调用,这可能是您的模式造成的:为什么要创建一个新的类作为数据源,而不使用NSCollectionView所在的相同的NSViewController呢?
我总是这样做,并且使用新的API都能很好地工作。希望这能帮到你!
发布于 2016-04-23 09:51:08
我几乎有同样的问题,下面是我解决这个问题的方法。
首先,我遇到的问题是:
我注释掉了委托中的每个NSCollectionViewDelegateFlowLayout方法,结果发现如果方法NSCollectionViewDelegateFlowLayout被注释掉了,那么一切都很好(尽管我不使用标头)。
结果发现,collectionView:layout:referenceSizeForHeaderInSection:返回的是一个NaN,而不是大小的0.0 (愚蠢的复制/粘贴错误)。
您确定您的布局返回的内容没有相同的问题吗?
发布于 2017-08-23 06:50:42
我遇到的问题是,我没有为集合视图的项注册nib或类。症状和你描述的完全一样-- numberOfItemsInSection被称为,而itemForRepresentedObjectAtIndexPath则不是。注册nib之后,将开始调用该方法。以下是相关的答案-- https://stackoverflow.com/a/39516035/4635852
https://stackoverflow.com/questions/35586996
复制相似问题