UICollectionView registerClass:forCellWithReuseIdentifier方法中断UICollectionView

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

“注册一个类用于创build新的集合视图单元格”。

当我尝试使用它时,我的项目收到黑色的collections视图。 当我删除它一切工作正常。

 #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; } 

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

  • numberOfItemsInSection
  • numberOfSectionsInCollectionView (不是必需的方法 – 参考这个评论 )
  • cellForItemAtIndexPath

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

另外,如果你正在寻找一个关于registerCell做什么以及如何使用它的好的解释,请查看这个链接并滚动到标题为“Cell and View Reuse”的底部。

同意RazorSharp的回答,并且想要指出在Techtopia链接中的关键词是:

如果单元类是用代码编写的,则使用UICollectionView的registerClass:方法执行注册,否则使用registerNib