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,请连接您的dataSource和delegate,并添加了所有必需的方法:
numberOfItemsInSectionnumberOfSectionsInCollectionViewcellForItemAtIndexPath然后不需要registerClass/ registerCell方法.但是,如果您需要重用视图,数据或单元格,那么您应该使用这些方法,以便iOS可以根据需要填充您的UICollectionView.这也可以通过设置Prototype Cell在您的Storyboard中完成(与registerClass方法的原理相同).
此外,如果您正在寻找有关registerCell使用它的方法和使用方法的详细说明,请查看此链接并滚动到标题为"单元格和查看重用"的底部.
| 归档时间: |
|
| 查看次数: |
28337 次 |
| 最近记录: |