与iOS中的UICollectionView相似,在Mac开发中,我们也会常常用到NSCollectionView来展示内容,但在使用中,与iOS有较大差别,尤其对Mac开发新手来说,不得不到头文件中慢慢搜索,结果事倍功半,本文简示范基础用法,可以快速上手练习,好了,闲话少叙,开启工程实例,开发语言使用Swift3.0
创建工程

选择开发语言

添加NSCollectionView

设置约束

设置连线属性

添加自定义CollectionViewItem



实现代码(ViewController.swift)

CustomItem.swift

运行效果

Demo示例地址:
网友评论
在viewDidLoad中:
NSCollectionView *c = [[NSCollectionView alloc]initWithFrame:self.view.bounds];
NSCollectionViewFlowLayout *layout = [[NSCollectionViewFlowLayout alloc]init];
c.collectionViewLayout = layout;
[c registerClass:[CItem class] forItemWithIdentifier:@"ccc"]; // 这里的CItem是继承自NSCollectionViewItem的自定义类,如果不用自定义item,你也可以使用系统的
c.dataSource = self;
_cv = c;
NSClipView *clip = [[NSClipView alloc]initWithFrame:self.view.bounds];
clip.documentView = c;
NSScrollView *scrollView = [[NSScrollView alloc]initWithFrame:self.view.bounds];
[scrollView setContentView:clip];
[self.view addSubview:scrollView];
然后就是实现NSCollectionView的数据方法(代理方法也同理)
- (NSInteger)collectionView:(NSCollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 10;
}
- (NSCollectionViewItem *)collectionView:(NSCollectionView *)collectionView itemForRepresentedObjectAtIndexPath:(NSIndexPath *)indexPath{
return [collectionView makeItemWithIdentifier:@"ccc" forIndexPath:indexPath];
}