本文示範如何以純程式碼(不使用 xib)建立並使用 UICollectionView。
使用純程式碼時,必須透過以下方法之一註冊 Cell 或補充視圖:
- (void)registerClass:forCellWithReuseIdentifier:
- (void)registerClass:forSupplementaryViewOfKind:withReuseIdentifier:
- (void)registerNib:forCellWithReuseIdentifier:
- (void)registerNib:forSupplementaryViewOfKind:withReuseIdentifier:- (void)viewDidLoad
{
// 初始化
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, kNavHeight, kDeviceWidth, kDeviceHeight - kNavHeight*2 - kTabBarHeight - 20) collectionViewLayout:flowLayout];
// 註冊
[self.collectionView registerClass:[VideoCell class] forCellWithReuseIdentifier:@"cell"];
// 設置代理
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
[self.view addSubview:self.collectionView];
}#pragma mark - collectionView delegate
// 設置分區
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
// 每個分區上的元素個數
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 24;
}
// 設置元素內容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identify = @"cell";
VideoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
[cell sizeToFit];
VideoModel *model = [self.videoModels objectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString:model.videoImgURL];
[cell.imgView setImageWithURL:url];
cell.titleLabel.text = model.videoTitle;
return cell;
}
// 設置元素內縮邊距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
UIEdgeInsets top = {5, 10, 15, 5};
return top;
}
// 設置元素大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(240, (kDeviceHeight - kNavHeight*2 - kTabBarHeight - 20) / 4.0);
}
// 點擊元素觸發事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"%@", indexPath);
DetailVideoViewController *detailVC = [[DetailVideoViewController alloc] init];
[self.navigationController pushViewController:detailVC animated:YES];
}透過以上步驟,即可完全以純程式碼完成一個可捲動、可點擊的 UICollectionView,並自訂每個元素的大小與間距。