【问题标题】:UICollectionView with no XIB, UICollectionViewCell with XIB不带 XIB 的 UICollectionView,带 XIB 的 UICollectionViewCell
【发布时间】: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。

【问题讨论】:

    标签: objective-c xcode uicollectionview xib uicollectionviewcell


    【解决方案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
      猜你喜欢
      • 2018-04-21
      • 1970-01-01
      • 2014-06-03
      • 1970-01-01
      • 2021-09-23
      • 2015-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多