不带 XIB 的 UICollectionView,带 XIB 的 UICollectionViewCell

Posted

技术标签:

【中文标题】不带 XIB 的 UICollectionView,带 XIB 的 UICollectionViewCell【英文标题】:UICollectionView with no XIB, UICollectionViewCell with XIB 【发布时间】:2014-06-11 05:35:57 【问题描述】:

我正在尝试为我正在创建的没有 XIB 文件的 UICollectionView 创建一个带有 XIB 文件的 UICollectionViewCell。

以下是我创建 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 文件中,我将自定义类设置为 CustomCell - 但是当我加载集合视图时,我只看到矩形 - 而不是我为自定义类创建的 XIB。

【问题讨论】:

【参考方案1】:

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

文档here

【讨论】:

【参考方案2】:

viewDidLoad注册笔尖,如:

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];

快乐编码:)

【讨论】:

那里有 50%。注册 nib 是正确的,但是集合视图会在它出列时处理加载它,因此第二部分不是必需的。【参考方案3】:

尝试像下面这样加载 xib 单元格

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

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

【讨论】:

这样我不是失去了出队吗? CustomCell *cell = deque...(您在这一行中的代码),然后编写答案中的 nsarray 代码,然后 cell =[nibObjects objectAtIndex:0];或者你也可以检查条件 if(cell == nil)write first line which is in this ans and than cell =[nibObjects objectAtIndex:0]; 我回滚了对您问题的编辑,因为它基本上是另一个用户的重写。我希望没关系。 @Nisha - 不要在编辑中重写整个答案。我不敢相信它被批准了。 ...虽然两个版本的答案都是错误的。您将在哪里获得使用此代码的机会?【参考方案4】:

使用以下语句注册类:

[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier: carouselItemReuseIdentifier];

【讨论】:

这个确切的代码已经在问题中了,它首先是问题的原因,所以-1

以上是关于不带 XIB 的 UICollectionView,带 XIB 的 UICollectionViewCell的主要内容,如果未能解决你的问题,请参考以下文章

将附加视图插入从 Xib 加载的 UICollectionView

自定义 XIB 中的静态 UITableView 或 UICollectionView?

从 xib 加载单元格时删除 UICollectionView 中的边框

使用 Xib 创建 UICollectionView/UICollectionViewController 组件并在 UIViewController 中实现

UICollectionView 自定义组头组尾的XIB方法

通过Xib创建 UICollectionView 和自定义UICollectionViewCell