没有XIB的UICollectionView,带XIB的UICollectionViewCell

时间:2014-06-11 05:35:57

标签: objective-c xcode uicollectionview xib uicollectionviewcell

我尝试使用XIB文件为UICollectionView创建一个UICollectionViewCell,而不创建XIB文件。

以下是我创建CollectionView的方法:

_collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:collectionViewFlowLayout];
    [_collectionView setDelegate:self];
    [_collectionView setDataSource:self];
    [_collectionView setBackgroundColor:[UIColor clearColor]];
    [_collectionView registerClass:[CustomCell class] forCellWithReuseIdentifier:carouselItemReuseIdentifier];
    [self.view addSubview:_collectionView];

以下是我如何调用自定义单元格:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:carouselItemReuseIdentifier forIndexPath:indexPath];
    [cell refreshWithData];

    return cell;
}

在XIB文件中,我将Custom Class设置为CustomCell - 但是当我加载集合视图时,我只看到矩形 - 而不是我为自定义类创建的XIB。

4 个答案:

答案 0 :(得分:1)

您需要使用registerNib:forCellWithReuseIdentifier:注册 nib ,而不是类。注册课程只意味着它对你在笔尖中添加的内容一无所知。

文档here

答案 1 :(得分:1)

viewDidLoad中注册nib,如:

UINib *nib = [UINib nibWithNibName:@"MyCell" bundle: nil];
[cv registerNib:nib forCellWithReuseIdentifier:identifier];

并在单元格方法中:

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

CustomCell *cell = [nibObjects objectAtIndex:0];

快乐编码:)

答案 2 :(得分:0)

尝试加载xib单元格,如下所示

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

CustomCell *cell = = [nibObjects objectAtIndex:0];

答案 3 :(得分:-1)

使用以下语句注册该类:

[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier: carouselItemReuseIdentifier];
相关问题