我正在尝试NSCollectionView 在El Capitan中引入的新API.
在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)
}
}
Run Code Online (Sandbox Code Playgroud)
之后,我创建了一个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
}
}
Run Code Online (Sandbox Code Playgroud)
该问题是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()]
Run Code Online (Sandbox Code Playgroud)
我可以在superview中清楚地看到集合视图,但是没有单元格.
此外,如果在委托之外调用此行(但在注册单元类之后)会导致应用程序崩溃!
let item = collectionView.makeItemWithIdentifier("cell", forIndexPath: /*any index path*/)
Run Code Online (Sandbox Code Playgroud)
我做错了什么或NSCollectionView新的API坏了吗?
谢谢.
makeItemWithIdentifier方法 至关重要,它会在您的包中查找名为“cell”的 .xib:如果它来自另一个包,您可能需要使用registerNib:forItemWithIdentifier:来注册它。
因此,您的问题在此之前出现,因为您的collectionView:itemForRepresentedObjectAtIndexPath永远不会被调用,这可能是由您的模式引起的:为什么您创建一个新类来充当数据源,而不使用 NSCollectionView 所在的相同 NSViewController ?
我总是这样做,并且使用新的 API 一切都完美。希望这可以帮助你!