macos開發-NSCollectionView

一. 簡述

以可自定義的布局顯示的數據項的有序集合。

@interface NSCollectionView : NSView
Merging content and layout to create the final appearance

二. 官方屬性方法

// 為收集視圖提供數據的對象
@property (nullable, weak) id<NSCollectionViewDataSource> dataSource API_AVAILABLE(macos(10.11)); 
@property (nullable, weak) id<NSCollectionViewPrefetching> prefetchDataSource API_AVAILABLE(macos(10.13));
// 委托對象
@property (nullable, weak) id<NSCollectionViewDelegate> delegate;
// 為收集視圖提供數據的數組
@property (copy) NSArray<id> *content;
@property (nullable, strong) NSView *backgroundView API_AVAILABLE(macos(10.11));
// 背景色數組
@property (null_resettable, copy) NSArray<NSColor *> *backgroundColors;
// 背景視圖是否隨項目及其他內容滾動
@property BOOL backgroundViewScrollsWithContent API_AVAILABLE(macos(10.12));
// 構建集合視圖內容的布局對象
@property (nullable, strong) __kindof NSCollectionViewLayout *collectionViewLayout API_AVAILABLE(macos(10.11));

!!! 之后再補充 !!!

三. 示例

1. 效果圖

要達到的效果:

  • 顯示左側聊天列表
  • Split滑動item內控件位置不變動
  • 全屏下的顯示
  • 點擊item調整選中色

如下圖

效果圖

2. 具體代碼

2.1 創建NSCollectionView

此處為了方便使用Storyboard創建

創建CollectionView

2.2 配置flowLayout(可以創建或者代理設置)

self.flowLayout = [[NSCollectionViewFlowLayout alloc] init];
self.flowLayout.itemSize = NSMakeSize(self.collectionView.frame.size.width, 60); // item大小
self.flowLayout.minimumLineSpacing = 0; // 最小橫向間距
self.flowLayout.minimumInteritemSpacing = 0; // 最小豎向間距
self.collectionView.collectionViewLayout = self.flowLayout;

說明: 這里不使用Storyboard或者代理配置flowLayout的原因是在滑動SplitView的時候要調整itemSize,使用這種方式更方便設置itemSize

2.3 設置代理

@interface FSMessageVC ()
<
NSSplitViewDelegate,
NSCollectionViewDelegate,
NSCollectionViewDataSource,
NSCollectionViewDelegateFlowLayout
>

self.collectionView.delegate = self;
self.collectionView.dataSource = self;

2.4 設置CollectionView屬性

// 設置CollectionView的背景色
self.collectionView.layer.backgroundColor = NSColor.whiteColor.CGColor;
self.collectionView.wantsLayer = YES;
// 設置可選擇 !!!注意!!!不設置為YES會導致點擊item無效果
self.collectionView.selectable = YES;

2.5 注冊自定義的Item

[self.collectionView registerNib:[[NSNib alloc] initWithNibNamed:@"FSChatCell" bundle:nil]
               forItemWithIdentifier:@"kChatItem"];

2.6 實現代理方法

// 區數
- (NSInteger)numberOfSectionsInCollectionView:(NSCollectionView *)collectionView {
    return 1;
}
// item數量
- (NSInteger)collectionView:(NSCollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataSource.count;
}
// FSChatCell繼承自NSCollectionViewItem
- (nonnull NSCollectionViewItem *)collectionView:(nonnull NSCollectionView *)collectionView itemForRepresentedObjectAtIndexPath:(nonnull NSIndexPath *)indexPath {
    FSChatCell *cell = (FSChatCell *)[collectionView makeItemWithIdentifier:@"kChatItem" forIndexPath:indexPath];
    cell.name = self.dataSource[indexPath.item];
    return cell;
}

- (BOOL)commitEditingAndReturnError:(NSError *__autoreleasing  _Nullable * _Nullable)error {
    return YES;
}

- (void)encodeWithCoder:(nonnull NSCoder *)coder {
    
}

2.7 Split滑動item內控件位置不變動

// 1. 添加NSSplitViewDelegate
self.splitView.delegate = self;

// 最小可滑動的點
- (CGFloat)splitView:(NSSplitView *)splitView constrainMinCoordinate:(CGFloat)proposedMinimumPosition ofSubviewAt:(NSInteger)dividerIndex {
    return 200;
}
// 最大可滑動的點
- (CGFloat)splitView:(NSSplitView *)splitView constrainMaxCoordinate:(CGFloat)proposedMaximumPosition ofSubviewAt:(NSInteger)dividerIndex {
    return 300;
}
// 滑動時的通知代理, 設置itemSize
- (void)splitViewDidResizeSubviews:(NSNotification *)notification {
    self.flowLayout.itemSize = NSMakeSize(self.collectionView.frame.size.width, 60);
}

2.8 全屏下的顯示

添加全屏通知在通知的回調方法里調用 self.flowLayout.itemSize = NSMakeSize(self.collectionView.frame.size.width, 60); ,比較簡單不再累述。

2.9 點擊item調整選中背景色

有兩種方式實現:

  • didSelectItemsAtIndexPathsdidDeselectItemsAtIndexPaths修改item背景色
  • 在自定義item中重寫selected方法
// 方式 1
- (void)collectionView:(NSCollectionView *)collectionView didSelectItemsAtIndexPaths:(NSSet<NSIndexPath *> *)indexPaths {
    NSIndexPath *indexPath = indexPaths.allObjects.firstObject;
    FSChatCell *cell = (FSChatCell *)[collectionView itemAtIndexPath:indexPath];
    cell.view.wantsLayer = YES;
    cell.view.layer.backgroundColor = NSColor.lightGrayColor.CGColor;
}

- (void)collectionView:(NSCollectionView *)collectionView didDeselectItemsAtIndexPaths:(NSSet<NSIndexPath *> *)indexPaths {
    NSIndexPath *indexPath = indexPaths.allObjects.firstObject;
    FSChatCell *cell = (FSChatCell *)[collectionView itemAtIndexPath:indexPath];
    cell.view.wantsLayer = YES;
    cell.view.layer.backgroundColor = NSColor.whiteColor.CGColor;
}

// 方式 2 
//  FSChatCell.m
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.wantsLayer = YES;
      self.view.layer.backgroundColor = NSColor.whiteColor.CGColor;
}

- (void)setSelected:(BOOL)selected {
    super.selected = selected;
    [self changeBgViewColor];
}

- (void)changeBgViewColor {
    if (self.selected) {
        if (self.highlightState == NSCollectionViewItemHighlightForSelection) {
            self.view.layer.backgroundColor = NSColor.lightGrayColor.CGColor;
        } else if (self.highlightState == NSCollectionViewItemHighlightNone ||
                   self.highlightState == NSCollectionViewItemHighlightForDeselection) {
            self.view.layer.backgroundColor = NSColor.whiteColor.CGColor;
        }
    } else {
        self.view.layer.backgroundColor = NSColor.whiteColor.CGColor;
    }
}

2.10 FSChatCell.xib

說明:

  • 創建Object對象并綁定FSChatCell
image-20201109174544750
  • 連線時最好將控件連在創建的Objects-ChatCell上
image-20201109174737345

2.11 添加頭/尾

  • 創建FSChatHeaderView

    FSChatHeaderView繼承自NSView

  • 注冊HeaderView

    [self.collectionView registerNib:[[NSNib alloc] initWithNibNamed:@"FSChatHeaderView" bundle:nil]
              forSupplementaryViewOfKind:NSCollectionElementKindSectionHeader
                          withIdentifier:@"kChatHeader"];
    
  • 實現代理

- (NSSize)collectionView:(NSCollectionView *)collectionView layout:(NSCollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return NSMakeSize(self.collectionView.frame.size.width, 40);
}

- (NSView *)collectionView:(NSCollectionView *)collectionView
viewForSupplementaryElementOfKind:(NSCollectionViewSupplementaryElementKind)kind
               atIndexPath:(NSIndexPath *)indexPath {
    FSChatHeaderView *headerView = [collectionView makeSupplementaryViewOfKind:NSCollectionElementKindSectionHeader
                                                                withIdentifier:@"kChatHeader"
                                                                  forIndexPath:indexPath];
    return headerView;
}

Github Demo

說明:

  • registerNib/registerClass可以寫成宏,代碼可以更整潔。
#pragma mark - 注冊Nib
#define kRegisterNibCollectionView(collectionView, cell, indetifier)    [collectionView registerNib:[[NSNib alloc] initWithNibNamed:NSStringFromClass([cell class]) bundle:nil] forItemWithIdentifier:indetifier]
#define kRegisterNibTableView(tableView, cell, indetifier)              [tableView registerNib:[[NSNib alloc] initWithNibNamed:NSStringFromClass([cell class]) bundle:nil] forCellReuseIdentifier:indetifier]
  • identifier可以寫成靜態常量

    static NSString *const kChatItemID = @"chatItemID";
    static NSString *const kChatHeaderID = @"chatHeaderID";
    
  • MVC/MVP/MVVM模式自己選擇,Demo使用MVC完成。

  • Demo只設置了頭部,尾部同理。


個人博客: ?? ForgetSou


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容