Search code examples
ioscellsubviewuicollectionviewuicollectionviewcell

UICollectionView cell: is it safe to bring cell.selectedBackgroundView to front?


I am just starting to implement a multiselect UICollectionView. Would the below be considered "safe" code (since i assume theres some reason it is called BackgroundView instead of AccessoryView or such) ? I had the idea to save some effort, i intend to keep track of the selected items at the indexpath for further use via an array.

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

 cell.selectedBackgroundView = someView_With_A_Checkmark_Image;
 [cell bringSubviewToFront:cell.selectedBackgroundView];

 //...
return cell;

}

Solution

  • Is it safe?? Ya of course it wont cause any error. If your backgroundView is above the contentView of the cell, then what is the significance of contentView??.

    Collection view cell structure
    enter image description here

    If you select an item in the collection view, collectionView will switch the BackgroundView and Selected background view. So what you can do is give valid views as background view and selected background view upon configuring your custom cell or change any properties of the cell in didSelectItem to differentiate selection. That is better.

    Then one more no need to keep track of selection using a separate array. [self.collectionView indexPathsForSelectedItems] will give you selected items path at any point of time