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,连接了你的dataSource
和delegate
,并且添加了所有必需的方法:
-
numberOfItemsInSection
numberOfSectionsInCollectionView
-
cellForItemAtIndexPath
那么registerClass
/ registerCell
方法是不需要的。 但是,如果您需要重用视图,数据或单元格,那么您应该使用这些方法,以便iOS可以根据需要填充您的UICollectionView。 这也可以通过设置原型单元 (原理与registerClass
方法相同)在Storyboard中完成。
另外,如果你正在寻找一个关于registerCell
做什么以及如何使用它的好的解释,请查看这个链接并滚动到标题为“Cell and View Reuse”的底部。
同意RazorSharp的回答,并且想要指出在Techtopia链接中的关键词是:
如果单元类是用代码编写的,则使用UICollectionView的registerClass:方法执行注册,否则使用registerNib
- 在NSOperation中取消NSData initWithContentsOfURL
- UITableCell AccessoryView:设置accessoryView等于UIImageView无限循环
- 雪碧套件纹理行事有趣
- 将MKMapView集中在引脚下方的N像素点上
- 即使我剩下大约80 MB的RAM,也会触发applicationDidReceiveMemoryWarning的虚假调用
- FBFriendPickerViewController在iOS上显示和清空表格。 放置选取器运行良好
- 保持UITextField可见性的扩展方法
- animationUITextField指示一个错误的密码
- 在iOS中用于扫描条形码(代码39格式)的免费SDK