我的应用程序中有一个集合视图,我希望它包含一个自定义单元格。我已经创建了一个自定义单元格视图xib文件。然后我在我的数据源方法中使用它:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
OtherCustomersCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:OTHER_CUSTOMERS_CELL_IDENTIFIER forIndexPath:indexPath];
if(cell == nil){
NSArray *nsObjects = [[NSBundle mainBundle] loadNibNamed:@"OtherCustomersCell" owner:nil options:nil];
for(id obj in nsObjects)
if([obj isKindOfClass:[OtherCustomersCell class]])
cell = (OtherCustomersCell*) obj;
}
[cell.name setText:@"AAAA BBBBB"];
return cell;
}
但是当我运行应用程序时,集合视图应该只有一个黑色矩形(位于表格视图的底部):
我做错了什么? 提前谢谢。
答案 0 :(得分:4)
集合视图与表视图的工作方式不同,因为如果无法出列,则不必创建单元格。
相反,您必须先为单元格注册nib:
- (void)viewDidLoad
{
...
UINib *cellNib = [UINib nibWithNibName:@"OtherCustomersCell" bundle:nil];
[collectionView registerNib:cellNib forCellWithReuseIdentifier:OTHER_CUSTOMERS_CELL_IDENTIFIER];
}
然后您可以将单元格出列,并在必要时自动为您创建:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
OtherCustomersCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:OTHER_CUSTOMERS_CELL_IDENTIFIER forIndexPath:indexPath]; // cell won't be nil, it's created for you if necessary!
[cell.name setText:@"AAAA BBBBB"];
return cell;
}
答案 1 :(得分:2)
您必须在viewdidload中以下列方式注册UICollectionView
实例,然后您可以使用它。
[self.photoListView registerNib:[UINib nibWithNibName:@"UIcollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"Identifier"];