UICollectionViewController的簡單使用

注冊CellId

static NSString *const XXCellId = @"XXCellId";

注冊Cell

[self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([XXCell class]) bundle:nil] forCellWithReuseIdentifier:XXCellId];

初始化&賦值

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

XXCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:XXCellId forIndexPath:indexPath];

cell.cellData = [[[self.XXModel.xxx objectAtIndex:indexPath.section] yyy] objectAtIndex:indexPath.item];

}

必須設置的布局

- (instancetype)init;

- (instancetype)init{

// 設置流水布局

UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];

layout.itemSize = CGSizeMake(100, 100);

// 設置最小行間距

layout.minimumLineSpacing = 2;

// 設置最小垂直間距

layout.minimumInteritemSpacing = 2;

// 設置滾動方向(默認垂直滾動)

layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

return [self initWithCollectionViewLayout:layout];

}

定義展示的Section的個數

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

return 2;

}

定義展示的UICollectionViewCell的個數

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

return 3;

}

定義每個UICollectionView 的大小

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

return CGSizeMake(80, 80);

}

定義每個UICollectionView 的 margin

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{

return UIEdgeInsetsMake(5, 10, 5, 10);

}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{

width 為水平滑動時,間距有效。height 為垂直滑動時,間距有效。

return CGSizeMake( width,height );

}

區頭 ? 與cell大概相同

static NSString *const HeaderViewId = @"HeaderViewId";

[self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([HeaderView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HeaderViewId];

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{

HeaderView *HeaderView ?= [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HeaderViewId forIndexPath:indexPath];

return HeaderView;

}

是否允許選中 默認否

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{

return YES;

}

選中的狀態

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

}

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

推薦閱讀更多精彩內容