UICollectionView registerClass:forCellWithReuseIdentifier方法中断UICollectionView

Jan*_*ski 28 objective-c ios uicollectionview uicollectionviewcell

registerClass:forCellWithReuseIdentifier:方法的作用是什么?根据Apple的开发者文档,它应该是

"注册一个类用于创建新的集合视图单元格."

当我尝试使用它我的项目时,我得到一个黑色的集合视图.当我删除它一切正常.

#define cellId @"cellId"
#import "ViewController.h"
#import "Cell.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property(strong, nonatomic)NSMutableArray * photoArray;


@end

@implementation ViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSLog(@"%@",_photoArray);
    _photoArray = [[NSMutableArray alloc]initWithCapacity:0];
    [_collectionView registerClass:[Cell class] forCellWithReuseIdentifier:cellId];
    for(int i=1;i<=12;i++)
    {
        NSString * imgName = [NSString stringWithFormat:@"%d.png",i];
        UIImage *img  = [UIImage imageNamed:imgName];
        [_photoArray addObject:img];
    }
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _photoArray.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    Cell* cell = [_collectionView  dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    cell.cellImage.image = [_photoArray objectAtIndex:indexPath.row];
    return cell;
}
Run Code Online (Sandbox Code Playgroud)

Sam*_*cer 35

如果您已经在Storyboard中创建了UICollectionView,请连接您的dataSourcedelegate,并添加了所有必需的方法:

  • numberOfItemsInSection
  • numberOfSectionsInCollectionView(不是必需的方法 - 请参阅此评论)
  • cellForItemAtIndexPath

然后不需要registerClass/ registerCell方法.但是,如果您需要重用视图,数据或单元格,那么您应该使用这些方法,以便iOS可以根据需要填充您的UICollectionView.这也可以通过设置Prototype Cell在您的Storyboard中完成(与registerClass方法的原理相同).

此外,如果您正在寻找有关registerCell使用它的方法和使用方法的详细说明,请查看此链接并滚动到标题为"单元格和查看重用"的底部.

  • 谢谢@RazorSharp.但是,只想指出`numberOfSectionsInCollectionView:`不是'必需的方法'.根据[Apple文档](http://developer.apple.com/library/ios/documentation/uikit/reference/UICollectionViewDataSource_protocol/Reference/Reference.html#//apple_ref/doc/uid/TP40012175-CH1-SW5), `如果未实现此方法,则集合视图使用默认值1.` (3认同)
  • 重点是您可以直接在故事板中连接原型单元,这与调用`registerClass:...`的作用相同.内存使用或单元重用实际上与此无关.集合视图永远不会将单元格加载到不在屏幕上的内存中,如果单元格标识符实际上没有注册,则单元格出列的行会崩溃. (2认同)