天天看点

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必须要写对