您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

手寫 UICollectionView 踩坑記:佈局參數與 Cell 註冊

編輯:iOS 開發綜合

平常習慣用 Storyboard 拉界面,一旦改成純手寫 UICollectionView,就會連撞兩個牆。本文記錄這兩個錯誤與解法,順帶整理官方文檔的相關說明。

問題一:必須傳入非空的 layout

UICollectionView must be initialized with a non-nil layout parameter
(集合視圖必須使用佈局參數初始化)

錯的寫法:

UICollectionView *first = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 320, 320)];
[self.view addSubview:first];

改成正確寫法:

UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
UICollectionView *first = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 320, 320)
                                              collectionViewLayout:flowLayout];
[self.view addSubview:first];

官方文檔對兩個參數的說明:

frame — The frame rectangle for the collection view, measured in points. The origin of the frame is relative to the superview in which you plan to add it. This frame is passed to the superclass during initialization.

layout — The layout object to use for organizing items. The collection view stores a strong reference to the specified object. Must not be nil.

結論很明確:UICollectionView 沒有預設佈局,必須自己給一個,而且初始化的時候就要給。

問題二:Cell 復用崩潰

Assertion failure in -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewCategory:]

原因是 Storyboard 裡我們通常已經設好復用標識符與 Cell 類,手寫時這一步得自己補上。一行代碼解決:

[first registerClass:[UICollectionViewCell class]
  forCellWithReuseIdentifier:@"cell"];

可用的註冊方法一共有四個:

// 用類註冊
- (void)registerClass:forCellWithReuseIdentifier:
- (void)registerClass:forSupplementaryViewOfKind:withReuseIdentifier:

// 用 xib 註冊
- (void)registerNib:forCellWithReuseIdentifier:
- (void)registerNib:forSupplementaryViewOfKind:withReuseIdentifier:

完整可運行代碼

//
//  ViewController.m
//  手寫 UICollectionView
//

#import "ViewController.h"

#define WEIGHT [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height

@interface ViewController () <UICollectionViewDataSource,
                            UICollectionViewDelegateFlowLayout>
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - setup

- (void)setup {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    UICollectionView *first =
        [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WEIGHT, HEIGHT)
                            collectionViewLayout:flowLayout];

    // 註冊 cell,否則 dequeue 會崩潰
    [first registerClass:[UICollectionViewCell class]
  forCellWithReuseIdentifier:@"cell"];

    [self.view addSubview:first];
    first.dataSource = self;
    first.delegate   = self;
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 3;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView
     numberOfItemsInSection:(NSInteger)section {
    return 2;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identify = @"cell";
    UICollectionViewCell *cell =
        [collectionView dequeueReusableCellWithReuseIdentifier:identify
                                                 forIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor whiteColor];
    return cell;
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(WEIGHT / 3, WEIGHT / 3);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView
                   layout:(UICollectionViewLayout *)collectionViewLayout
minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return WEIGHT / 9;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                        layout:(UICollectionViewLayout *)collectionViewLayout
  insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(WEIGHT / 18, WEIGHT / 9, WEIGHT / 18, WEIGHT / 9);
}

@end

本文原創,轉載請註明出處。

順帶一提,如果界面結構固定且需要大量自適應排版,iOS 9 之後可以考慮 UICollectionViewCompositionalLayout,它用描述性的方式宣告列表、網格與分層結構,比手寫 FlowLayout 代理方法輕 <<

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