Subclassing UICollectionViewCell leads to never being selected

无人久伴 提交于 2019-12-11 02:15:47

问题


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.


回答1:


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!!



来源:https://stackoverflow.com/questions/15578915/subclassing-uicollectionviewcell-leads-to-never-being-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!