CollectionView.xib中创建多个nibCell,用的时候如何使用??

xib
如图:我在collection.xib中创建了2个cell,定义了不同的identifier,

使用的时候:

     NSArray *nibArrays = [[UINib nibWithNibName:@"LongCell" bundle:nil] instantiateWithOwner:nil options:nil];
    [collectionView registerClass:[[nibArrays objectAtIndex:0] class] forCellWithReuseIdentifier:@"LongCellFirst"];
    [collectionView registerClass:[[nibArrays objectAtIndex:1] class] forCellWithReuseIdentifier:@"LongCellSecond"];
#pragma mark - UICollectionViewDelegate DataSource -
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item % 2 == 0) {
        LongCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LongCellFirst" forIndexPath:indexPath];

        return cell;
    }else {
        LongCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LongCellSecond" forIndexPath:indexPath];
        return cell;
    }
}

clipboard.png

这样能运行,但是取出的cell都是上面什么也没有。
是我注册cell不对吗??还是因为不能这样用?tableViewCell.xib就可以这样搞啊?
tableView.xib中创建多个cell
请大神解释啊。。。。。。

阅读 9.9k
6 个回答

你是用nib创建的啊,不应该用registerNib来注册吗?为什么用regClass。

xib文件读取错了
NSArray *nibArrays=[[NSBundle mainBundle]loadNibNamed:@"LongCell" owner:nil options:nil];

两种方法:

  1. 拆成两个 xib ,每次 registerNib: 一个;

  2. 合成一个,但是自己初始化实例:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        if (indexPath.row % 2) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LongCellFirst"];
            if (!cell) {
                cell = [[UINib nibWithNibName:@"LongCell" bundle:nil] instantiateWithOwner:self
                                                                                   options:nil].firstObject;
            }
    
            return cell;
        }
        else {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LongCellSecond"];
            if (!cell) {
                cell = [[UINib nibWithNibName:@"LongCell" bundle:nil] instantiateWithOwner:self
                                                                                   options:nil].lastObject;
            }
    
            return cell;
        }
    }

建议一个 xib 文件对应一个 View,没必要省文件吧

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题