ƒernando Valle
ƒernando Valle

Reputation: 3714

How add cell to UICollectionView programatically without storyBoard

I tried the follow code:

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

but I get the error:

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:'

I don't use a storyBoard so I don't know how to tackle this.

Upvotes: 2

Views: 2406

Answers (2)

Barlow Tucker
Barlow Tucker

Reputation: 6519

To register a cell for reuse in Swift, you would do the following when creating your CollectionView:

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

Then when getting your cell, you would have something like this:

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

  return cell
}

Upvotes: 0

CW0007007
CW0007007

Reputation: 5681

Two things wrong here.

Firstly when you create your collectionView you need to add this line

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

Then in your collectionView:cellForItemAtIndexPath: you create your cell like this:

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

Upvotes: 2

Related Questions