0
votes

So I have a UICollectionView and a custom cell and it all shows up and works great. I register the class in viewDidLoad:

myCollectionView = [[UICollectionView alloc] initWithFrame:collectionViewFrame collectionViewLayout:layout];
[myCollectionView setDataSource:self];
[myCollectionView setDelegate:self];
[myCollectionView setBackgroundColor:[UIColor myColor]];
[myCollectionView registerClass:[SBCustomCell class] forCellWithReuseIdentifier:@"Cell"];

In my cellForItemAtIndexPath method I dequeue the cell and set its properties and return it:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"Cell";

SBCustomCell *cell= [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

[cell setName: "My Name"];
cell.image = [UIImage imageNamed:@"lol.png"];
cell.score = 100.0;
cell.backgroundColor=[UIColor whiteColor];

return cell;
}

This all works fine and it shows up in the UI. My issue is when I set a gesture recognizer on the collectionView, when I long press a certain cell, I want to be able to access its properties. I am trying to do so as such:

-(void)handleLongPress:(UILongPressGestureRecognizer *)longPressRecognizer {

CGPoint locationPoint = [longPressRecognizer locationInView:myCollectionView];

if (longPressRecognizer.state == UIGestureRecognizerStateBegan) {

    NSIndexPath *indexPathOfMovingCell = [myCollectionView indexPathForItemAtPoint:locationPoint];

    SBCustomCell *cell= [myCollectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPathOfMovingCell];

    NSLog(@"%@",cell.name);

When I try to access any of my custom cell's properties, it is (null) in console. Why is that? What am I doing wrong?

2

2 Answers

2
votes

You need to use:

SBCustomCell* cell = (SBCustomCell*)[myCollectionView cellForItemAtIndexPath:indexPathOfMovingCell];

instead of:

SBCustomCell* cell = [myCollectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPathOfMovingCell];

Also, you are using SBSingleCandidateUnitView as the cell type instead of your SBCustomCell.

0
votes

It was because I wasn't setting my properties correctly. In my header file I need to be setting a property, aka @property ... UIImageView myImageView;

And in my CustomCell.m file I should be not overriding those setters and getters. Instead just alloc and initing them and adding them to the view.

And back in my ViewController.m I should have added the properties as such:

customcell.myImageView.image = [UIImage imageNamed:@"cartman.png"];