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

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


如图:我在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;
    }
}

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


按照上面说到的方法,可以显示cell,但cell里的控件设置时没有效果,请问楼主解决了吗?


在cell中关联cell上的控件时,如果你不做修改。你所有关联的控件都默认为cell1上的控件。通俗的讲也就是连线时默认的都是第一个cell上的控件


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


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


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


两种方法:

  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;
        }
    }
【热门文章】
【热门文章】