目录
一、在storyboard中创建NsCollectionView
1.找到CollectionView控件,并拖到View中
2.设置datasource
3.在代码中实现数据源相关方法。
//在头件中增加实现NSCollectionViewDataSource协议
@interface ViewController : NSViewController <NSCollectionViewDataSource>
//在didload中注册NSCollectionViewItem.
- (void)viewDidLoad {
[super viewDidLoad];
//NSCollectionViewItem不是一个view, 它继承于NSViewController 所以不能使用NIB方式。
//NSNib* numberNib = [[NSNib alloc] initWithNibNamed:@"numberItem" bundle:nil];
//[_collectionview registerNib:numberNib forItemWithIdentifier:@"demo"];
[_collectionview registerClass:numberItem.self forItemWithIdentifier:@"demo"];
}
//返回每个Item
- (nonnull NSCollectionViewItem *)collectionView:(nonnull NSCollectionView *)collectionView itemForRepresentedObjectAtIndexPath:(nonnull NSIndexPath *)indexPath {
NSCollectionViewItem* item = [collectionView makeItemWithIdentifier:@"demo" forIndexPath:indexPath];
return item;
}
//返回每组中的item数量
- (NSInteger)collectionView:(nonnull NSCollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 8;
}
- (BOOL)commitEditingAndReturnError:(NSError * _Nullable __autoreleasing * _Nullable)error {
return YES;
}
- (void)encodeWithCoder:(nonnull NSCoder *)aCoder {
}
4、创建NIB方式的Item
5.实现效果
二、给item添加图片,最终结果跟工程如下:
工程附件请查我的CSDN相关下载,文件名为 :MacOS开发(OC)----NSCollectionView类相关属性跟方法附件
三、添加分组
//注册Hearder(HeaderView继承于NSView所以可以用XIB方式)
NSNib* headerNib = [[NSNib alloc] initWithNibNamed:@"numberItem" bundle:nil];
[_collectionview registerNib:headerNib forSupplementaryViewOfKind:NSCollectionElementKindSectionHeader withIdentifier:@"header"];
//返回组的数量
-(NSInteger)numberOfSectionsInCollectionView:(NSCollectionView *)collectionView
{
return 4;
}
//返回每组Header 或都Footer的视图
-(NSView *)collectionView:(NSCollectionView *)collectionView viewForSupplementaryElementOfKind:(NSCollectionViewSupplementaryElementKind)kind atIndexPath:(NSIndexPath *)indexPath
{
NSView* headerview = [collectionView makeSupplementaryViewOfKind:NSCollectionElementKindSectionHeader withIdentifier:@"header" forIndexPath:indexPath];
return headerview;
}
四、设置代理,响应事件
实现代理NSCollectionViewDelegate的方法
//选中item调用这个方法
- (void)collectionView:(NSCollectionView *)collectionView didSelectItemsAtIndexPaths:(NSSet<NSIndexPath *> *)indexPaths
{
}
//取消选中调用代理的这个方法
- (void)collectionView:(NSCollectionView *)collectionView didDeselectItemsAtIndexPaths:(NSSet<NSIndexPath *> *)indexPaths
{
}
//设置属性selection为selectable,表示可以选择。
五、设置Header的悬停效果
[(NSCollectionViewFlowLayout*)(_collectionview.collectionViewLayout) setSectionHeadersPinToVisibleBounds:TRUE];