天天看點

UICollectionView的一些常見問題

情況一,UIColectionView的cell不顯示,

 解決方法:在cell的.m檔案裡添加如下方法代碼,YXNewsCollectionViewCell是目前cell的檔案名

-(instancetype)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        // 在此添加

        // 初始化時加載collectionCell.xib檔案

        NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"YXNewsCollectionViewCell" owner:self options: nil];

        // 如果路徑不存在,return nil

        if(arrayOfViews.count < 1){return nil;}

        // 如果xib中view不屬于UICollectionViewCell類,return nil

        if(![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]){

            return nil;

        }

        // 加載nib

        self = [arrayOfViews objectAtIndex:0];

    }

    return self;

}

問題二,設定了CollectionView的行間距為0,可還是有一個間距

解決方法:在controller中添加如下方法

// 設定隻有當間距小于該值時,cell會進行換行

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {

        return 0;

}

問題三,運作項目崩掉,log日志是:

reason: 'could not dequeue a view of kind: UICollectionElementKindCell with identifier cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

需要在注冊UICollectionViewCell,代碼如下

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

注釋:如果是自定義的cell,UICollectionViewCell需要替換成自定義的cell檔案名,Identifier必須要寫對