如何在没有storyBoard的情况下以编程方式将单元格添加到UICollectionView

时间:2014-08-19 06:46:39

标签: ios uicollectionview nib

我尝试了以下代码:

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

    Pictograma *pictograma;

    pictograma = [pictogramas objectAtIndex:indexPath.row];

    AddPictogramaCell *newCell = [[AddPictogramaCell alloc] initWithFrame:CGRectMake(0, 0, 200, 200) pictograma:pictograma];

    [newCell.nombre setText:pictograma.nombre];
    [newCell.imageView setImage:[UIImage imageWithContentsOfFile:pictograma.path]];

    newCell.pictograma = pictograma;

    return newCell;
}

但是我收到了错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason:
'the cell returned from -collectionView:cellForItemAtIndexPath: does not have a reuseIdentifier - cells must be retrieved by calling -
dequeueReusableCellWithReuseIdentifier:forIndexPath:'

我没有使用故事板,所以我不知道如何解决这个问题。

2 个答案:

答案 0 :(得分:2)

这里有两件事不对。

首先,当您创建collectionView时,需要添加此行

[collectionView registerClass:[AddPictogramaCell class] forCellWithReuseIdentifier:@"YOUR_IDENTIFIER"];

然后在你的collectionView:cellForItemAtIndexPath:中创建你的单元格:

AddPictogramaCell *newCell = (AddPictogramaCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"YOUR_IDENTIFIER" forIndexPath:indexPath];

答案 1 :(得分:0)

要在Swift中注册要重用的单元格,您可以在创建CollectionView时执行以下操作:

collectionView.registerClass(AddPictogramaCell, forCellWithReuseIdentifier: "YOUR_IDENTIFIER")

然后当你获得你的细胞时,你会得到这样的东西:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
  let cell:AddPictogramaCell = collectionView.dequeueReusableCellWithReuseIdentifier("", forIndexPath: indexPath) as! AddPictogramaCell

  return cell
}