您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS UICollectionView 純程式碼實現(無 xib)

編輯:iOS 相關資訊

本文示範如何以純程式碼(不使用 xib)建立並使用 UICollectionView。

註冊 Cell 的方式

使用純程式碼時,必須透過以下方法之一註冊 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];
}

實現 DataSource 與 Delegate 方法

#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,並自訂每個元素的大小與間距。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved