Padin215
Padin215

Reputation: 7484

Subclassing UICollectionViewCell leads to never being selected

I've tried subclassing a UICollectionViewCell and loading from a nib file:

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"DatasetCell" owner:self options:nil];

        if ([arrayOfViews count] < 1) {
            return nil;
        }

        if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]) {
            return nil;
        }

        self = [arrayOfViews objectAtIndex:0];

        UIView *view = [UIView new];
        view.frame = self.frame;
        view.backgroundColor = [UIColor orangeColor];
        self.selectedBackgroundView = view;
    }

    return self;
}

I'm running into an issue where a cell is selected, the cell.selected is not being set. It is always NO which is leading to an issue of deselecting the cells.

How do I handle getting the cell to the selected state?

EDIT:

I originally loading the custom UICollectionViewCell as a class:

[collectionView registerClass:[DatasetCell class] forCellWithReuseIdentifier:@"dataCell"];

Switched to loading the nib:

[collectionView registerNib:[UINib nibWithNibName:@"DatasetCell" bundle:nil] forCellWithReuseIdentifier:@"nibCell"];

I have the same select/deselect issue both ways.

Upvotes: 2

Views: 2824

Answers (1)

Martin R
Martin R

Reputation: 540105

The main error is that you have defined a property

@property (nonatomic) BOOL isSelected;

in your custom UICollectionViewCell subclass (in "DatasetCell.h"), which interferes with the inherited "selected" property of UICollectionViewCell.

If you remove that property definition, selection and deselection works as expected, at least for the cells loaded from the nib file via registerNib:....

For the cells loaded via registerClass:..., initWithFrame is called. You try to load the cell from the nib file there. That does not make much sense and seems not to work correctly. You should either create the cell programmatically in initWithFrame and use registerClass:, or create the cell in the nib file and use registerNib:.

initWithFrame is not called for cells loaded from the nib file, use awakeFromNib if you want to make modifications to the cell.

Hope that helps!!

Upvotes: 3

Related Questions