我正在尝试使用El Capitan中引入的新NSCollectionView 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) } }
之后,我创建了一个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坏了吗?
谢谢.