How to keep the didSelect action in UICollectionView in Objective-c? - ios

I have a UICollectionView and I add from my cellForItemAtIndexPath 12 cells. When I do scroll on this to see down cells, all functions is preserved, but when I do scroll to go up again, some cells don't execute the function loaded in didSelectItemAtIndexPath.
I set disabled some rows. But not the row that I clicked Why could be this? Could be a bad prepare for reuse cell?
I'm trying the reuse function, but this only affect drawing the cell wrong or on the another position and the function added in didSelectItemAtIndexPath not work:
[self.myCollectionView reloadData];
[self.myCollectionView layoutIfNeeded];
NSArray *visibleItems = [self.myCollectionView indexPathsForVisibleItems];
NSIndexPath *currentItem = [visibleItems objectAtIndex:0];
NSIndexPath *nextItem = [NSIndexPath indexPathForItem:currentItem.item + 1 inSection:currentItem.section];
[self.myCollectionView scrollToItemAtIndexPath:nextItem atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
WHen I do scroll and the do click to one cell, this not open my secondViewController, I think that this cell is gettin a wrong index that was disabled.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MyViewController *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"myCell" forIndexPath:indexPath];
switch ([indexPath row]) {
case 0:
titleCell= #"Title0";
detailCell=#"Detail0";
if([indexPath row]==2){
[cell setUserInteractionEnabled:NO];//Here I set disable Could be the problem caused by this??
}
[cell.image setHidden:YES];
cell.image.contentMode = UIViewContentModeScaleAspectFit;
break;
//Here other cases with the same structure
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
[collectionView deselectItemAtIndexPath:indexPath animated:NO];
MySecondClass *secondClass = [self.storyboard instantiateViewControllerWithIdentifier:#"myVC"];
[self.navigationController pushViewController:secondClass animated:YES];
}
-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
//Here assign yellow background color to first row and white color to the second row
}
And in my cell class I added the prepareForReuse but this not work...
- (void)prepareForReuse {
[super prepareForReuse];
[self removeFromSuperview];
[self setNeedsLayout];
}

The problem lies on this piece of code:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MyViewController *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"myCell" forIndexPath:indexPath];
switch ([indexPath row]) {
case 0:
titleCell= #"Title0";
detailCell=#"Detail0";
if([indexPath row]==2){
[cell setUserInteractionEnabled:NO];//Here I set disable Could be the problem caused by this??
}
[cell.image setHidden:YES];
cell.image.contentMode = UIViewContentModeScaleAspectFit;
break;
return cell;
}
Because cells are reusable. So the cell that you disabled earlier (For example cell0) will continue to be reused. When you scroll, that cell0 will become cell11 for example. However, its setting is still disabled.
You need to add a else statement to remove the disabled setting like this.
if([indexPath row]==2){
[cell setUserInteractionEnabled:NO];//Here I set disable Could be the problem caused by this??
}
else{
[cell setUserInteractionEnabled:YES];
}

When a cell scrolls off the screen it is potentially deallocated or (more likely) recycled, so any state you have in that cell is not persisted once its off screen. The solution is that you should check if a cell is selected and update its appearance in cellForRowAtIndexPath. You can just have didSelectItemAtIndexPath and didDeselectItemAtIndexPath call reloadRowsAtIndexPath and cellForRowAtIndexPath will handle all of the highlighting appearance logic in one place.

Related

collectionviewcell didSelectItemAtIndexPath/didDeselectItemAtIndexPath not responding for specific cells

I am trying to preselect some of the cell according to condition, which sets those cells selected and also change its background color while drawing those cells. Now the method
didSelectItemAtIndexPath / didDeselectItemAtIndexPath
is not getting called only for those preselected cells and hence I am not able to toggle selection and background color. The select/deselect delegate methods are being called for other cells
-(UICollectionViewCell*) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"cellForItemAtIndexPath: %#", indexPath);
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"collectionViewCell" forIndexPath:indexPath];
if(indexPath.row != 0 && indexPath.row != 8 && indexPath.section != 0 && indexPath.section != 25){
NSMutableDictionary *blockedHours = [blockedDaysArray objectAtIndex:indexPath.row-1];
NSString *blockedVal = [blockedHours valueForKey:#(indexPath.section-1).stringValue];
[cell setBlockedVal:(NSString*)blockedVal];
}
[cell addDayTimeLable:indexPath];
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"didSelectItemAtIndexPath: %# ", indexPath);
NSMutableDictionary *blockedHours = [blockedDaysArray objectAtIndex:indexPath.row-1];
[blockedHours setValue:#"1" forKey:#(indexPath.section-1).stringValue];
CollectionViewCell *cell = (CollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
cell.selected = YES;
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"didDeselectItemAtIndexPath %#", indexPath);
NSMutableDictionary *blockedHours = [blockedDaysArray objectAtIndex:indexPath.row-1];
[blockedHours setValue:#"0" forKey:#(indexPath.section-1).stringValue];
CollectionViewCell *cell = (CollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
cell.selected = NO;
}
In CollectionViewCell.m:
Self.selected calls the setter method and hence chagnes the background color
-(void)setBlockedVal:(NSString*)blockedVal{
if([blockedVal isEqualToString:#"1"]){
self.selected = YES;
}
}
-(void)setSelected:(BOOL)selected{
NSLog(#"set selected: %d", selected);
[super setSelected:selected];
if(selected)
self.backgroundColor = [SFIColors lightGreenColor];
else
self.backgroundColor = [UIColor whiteColor];
}
Note:
(1) didHighlightItemAtIndexPath/didUnHighlightItemAtIndexPath are
getting called for preselected cells.
(2)I Just found out that setting selected via didselect/didunselect is
redundant and I just removed from my code.Noticed that setSeleted is
auto called on clicking the other cells. Still this setSelected is not
being for preselected cells
Any Inputs to fix this or another way that I can do my task would be of great help.
I found the answer in this link: UICollectionView - didDeselectItemAtIndexPath not called if cell is selected
I actually searched a lot actually, but only now I found this link.
I had let my collection view know about my selection and that did the trick:
[collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];

UICollectionView Static CustomCell reuse

I have a problem i create UICollectionView with custom cell to display items. But after refresh of the UICollectionView reusable cell populate for wrong index
UICollectionView before refresh.
UICollectionView after refresh.
Code example of the reusable collection view cell.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
GalleryCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
if (indexPath.item != 0)
{
[cell setCollectionItem:[collectionData_ objectAtIndex:indexPath.row - 1]];
}
return cell;
}
Think it's reusing another cell (the balloon in this case) and is not setting anything for the first index cell. If you make an else statement to create a new camera cell, hopefully it will reappear.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
GalleryCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
if (indexPath.item != 0) {
[cell setCollectionItem:[collectionData_ objectAtIndex:indexPath.row - 1]];
} else {
// Set camera item here
}
return cell;
}
This problem occurs because the cells will be reused. Cells are reused to improve the performance of the system. If your table has 1000 cells, the system does not allocate 1000 cells but a much lower then reuse-
Try with adding else clause to the if
if (indexPath.item != 0)
{
[cell setCollectionItem:[collectionData_ objectAtIndex:indexPath.row - 1]];
}
else
{
//Set your cell at index 0 with your camera image
[cell setCollectionItem:#"camera-image"];
}

UICollectionView cell dequeue issue with custom selection view

I have a very frustrating problem with UICollectionView and its dequeuing mechanism.
In a nutshell, I have a custom UIView with a label inside. I set this up as the selection background view in my custom cell as follows:
//My Custom Cell Class
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if(self){
_selectionView = (MyCustomView *)[[[NSBundle mainBundle] loadNibNamed:#"MyNibName" owner:self options:nil] objectAtIndex:0];
self.selectedBackgroundView = _selectionView;
[self bringSubviewToFront:_selectionView];
}
return self;
}
Note that all the layout work, etc for both the cell and selectedBackgroundView is done in the nibs.
Whenever the cell is selected, I'd like to set custom text in the label for selectionView so in my custom cell I also have the following method:
//In my Custom cell class
- (void) setSelectedViewLabelText:(NSString *)paramText{
if(!self.isSelected){
return;
}
self.selectionView.label.text = paramText;
}
To set the text I have in my UICollectionViewController:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
MyCellClass *selectedCell = (MyCellClass *)[self.collectionView cellForItemAtIndexPath:indexPath];
[selectedCell setSelectedViewLabelText:someString];
}
The problem is that whenever the UICollectionView recycles the cell, it inits them again and obviously the setSelectedViewLabelText method isn't called.
I have an annoying feeling that I may have to track the selected indexPaths and enumerate through them to see if a cell is selected and call the method, but I have potentially large data sets and can foresee how this will become a performance problem.... any ideas?
Thanks in advance!
Keep track of your selected cell, like:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
MyCellClass *selectedCell = (MyCellClass *)[self.collectionView cellForItemAtIndexPath:indexPath];
[selectedCell setSelectedViewLabelText:someString];
selectedIndexPath = indexPath;
}
In cellForItemAtIndexPath check indexPath:
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
//.......
if([selectedIndexPath isEqual:indexPath]){
[cell setSelectedViewLabelText:someString];
}
return cell;
}
Hope this helps.. :)

UICollectionView allowsMultipleSelelections not working

I am trying to make some photoPicker with CollectionView.
Have
allowsMultipleSelection = YES
Using following method
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
selectedPictures = [NSMutableArray array];
[selectedPictures addObject:[imagesArray objectAtIndex:indexPath.item]];
NSLog(#"Selected list:\n %#", selectedPictures);
NSLog(#"Objects in Array %i", selectedPictures.count);
}
While I am selecting cells, it's always adding to MutableArray only one object according it's indexPath. What could be an issue?
Why don't u keep the selectedPictures as a member variable
in your code
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
selectedPictures = [NSMutableArray array]; //keep on creation the new array on each selection
[selectedPictures addObject:[imagesArray objectAtIndex:indexPath.item]]; //adding the selected images means single image
NSLog(#"Selected list:\n %#", selectedPictures);
NSLog(#"Objects in Array %i", selectedPictures.count);
}
try this
put his in viewDidLoad
- (void)viewDidLoad
{
selectedPictures = [[NSMutableArray alloc]init]; //initilise hear
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
// selectedPictures = [NSMutableArray array]; //keep on creation the new array on each selection
[selectedPictures addObject:[imagesArray objectAtIndex:indexPath.item]]; //adding the selected images means single image to already initialised array
NSLog(#"Selected list:\n %#", selectedPictures);
NSLog(#"Objects in Array %i", selectedPictures.count);
}
Hope this helps u .. :)
it may be caused by not calling super. While the documentation for UICollectionReusableView fails to mention this, the documentation for UITableViewCell, which has the same method, does.
- (void)prepareForReuse
{
[super prepareForReuse]
// Your code here.
}
Old Answer:
This may be a bug with the UICollectionView.
What's happening is cells that were previously selected are being reused and maintain the selected state. The collection view isn't setting selected to "NO".
The solution is to reset the the selected state in prepareForReuse of the cell:
- (void)prepareForReuse
{
self.selected = NO;
}
If the reused cell is selected, the collection view will set selected to "YES" after prepareForReuse is called.
This is something the UICollectionView should be doing on it's own. Thankfully the solution is simple. Unfortunately I spent a ton of time working around this bug by tracking my own select state. I didn't realize why it was happening until I was working on another project with smaller cells.
Also Try this
I'm not seeing why this would take place. I do not believe the issue is the use of row vs item, though you really should use item. I can imagine, though, if your collection view has more than one section, that only looking at row/item but ignoring section would be a problem (i.e. it would select the same item number in every section).
To cut the Gordian knot, I'd suggest saving the NSIndexPath of the selected item, and then using that for the basis of comparison. That also makes it easy to render an optimization in didSelectItemAtIndexPath. Anyway, first define your property:
#property (nonatomic, strong) NSIndexPath *selectedItemIndexPath;
And then implement cellForItemAtIndexPath and didSelectItemAtIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
CollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
cell.imageView.image = ...
if (self.selectedItemIndexPath != nil && [indexPath compare:self.selectedItemIndexPath] == NSOrderedSame) {
cell.imageView.layer.borderColor = [[UIColor redColor] CGColor];
cell.imageView.layer.borderWidth = 4.0;
} else {
cell.imageView.layer.borderColor = nil;
cell.imageView.layer.borderWidth = 0.0;
}
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
// always reload the selected cell, so we will add the border to that cell
NSMutableArray *indexPaths = [NSMutableArray arrayWithObject:indexPath];
if (self.selectedItemIndexPath)
{
// if we had a previously selected cell
if ([indexPath compare:self.selectedItemIndexPath] == NSOrderedSame)
{
// if it's the same as the one we just tapped on, then we're unselecting it
self.selectedItemIndexPath = nil;
}
else
{
// if it's different, then add that old one to our list of cells to reload, and
// save the currently selected indexPath
[indexPaths addObject:self.selectedItemIndexPath];
self.selectedItemIndexPath = indexPath;
}
}
else
{
// else, we didn't have previously selected cell, so we only need to save this indexPath for future reference
self.selectedItemIndexPath = indexPath;
}
// and now only reload only the cells that need updating
[collectionView reloadItemsAtIndexPaths:indexPaths];
}
Check also this
Your observation is correct. This behavior is happening due to the reuse of cells. But you dont have to do any thing with the prepareForReuse. Instead do your check in cellForItem and set the properties accordingly. Some thing like..
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cvCell" forIndexPath:indexPath];
if (cell.selected) {
cell.backgroundColor = [UIColor blueColor]; // highlight selection
}
else
{
cell.backgroundColor = [UIColor redColor]; // Default color
}
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
datasetCell.backgroundColor = [UIColor blueColor]; // highlight selection
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
datasetCell.backgroundColor = [UIColor redColor]; // Default color
}
I solved my issue;
The problem was very simple, I should have initialise MutableArray not in the Method didSelectItemAtIndexPath, but in the ViewDidLoad. Now it adding pictures one by one

Reusing cells UICollectionView - some cells don't get selected

In the UICollectionView, I've got a custom UICollectionViewCellClass, where prepareForReuse is overridden for default formatting staff.
I've got an NSMutableArray containing NSIndexPaths from didSelectItemAtIndexPath:.
In cellForItemAtIndexPath: I reformat the selected cells so they appear selected.
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
ButtonCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"ButtonCell" forIndexPath:indexPath];
NSString *title = self.ingredientsBook.names[indexPath.item];
cell.label.text = title;
if ([self isSelectedIndexPath:indexPath]){
cell.backgroundColor = [UIColor whiteColor];
cell.label.textColor = [UIColor blueColor];
}
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
self.searchButton.enabled = YES;
ButtonCell *cell = (ButtonCell *)[collectionView cellForItemAtIndexPath:indexPath];
[selectedCellIndexPaths addObject:indexPath];
NSLog(#"%#", selectedCellIndexPaths);
cell.backgroundColor = [UIColor whiteColor];
cell.label.textColor = [UIColor blueColor];
NSString *name = self.ingredientsBook.names[indexPath.item];
[self.selectedIngredientNames addObject:name];
}
The problem is that when I tap the first cell it's not possible to select the 16th or 17th.
Or if I tap the first three ones it's not possible to select the three last ones.
The didSelectItemAtIndexPath is not being called I suppose.
I feel that it has to be something really simple but I can't see it right now.
I tried to put NSLogsin shouldSelectItemAtIndexPath for understand if that method was called and the method is not being called at all. This happens when there's a distance of 16 cells between the selected one and the problematic one.
Here are other data source methods and isSelectedIndexPath:
-(BOOL)isSelectedIndexPath:(NSIndexPath *)indexPath{
for (NSIndexPath *test in selectedCellIndexPaths){
if (test == indexPath){
return YES;
}
}
return NO;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [self.ingredientsBook.names count];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"%#", indexPath);
return YES;
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
self.searchButton.enabled = ([[collectionView indexPathsForSelectedItems] count] > 0);
ButtonCell *cell = (ButtonCell *)[collectionView cellForItemAtIndexPath:indexPath];
cell.backgroundColor = [UIColor blackColor];
cell.label.textColor = [UIColor whiteColor];
[selectedCellIndexPaths removeObject:indexPath];
NSString *name = self.ingredientsBook.names[indexPath.item];
[self.selectedIngredientNames removeObject:name];
}
I found two problems. The prepareForReuse method seemed to be screwing things up, so I just deleted it. The main problem though, was the way you were implementing isSelectedIndexPath:. As soon as it finds the first selected item as you loop through the items, it returns YES and exits the loop. What you want to do, is just check if the indexPath is contained in the selectedCellIndexPaths array:
-(BOOL)isSelectedIndexPath:(NSIndexPath *)indexPath{
if ([selectedCellIndexPaths containsObject:indexPath]) {
return YES;
}else{
return NO;
}
}
Or, if you prefer to use a more succinct syntax, you can replace the if-else block with:
return ([selectedCellIndexPaths containsObject:indexPath])? YES : NO;
I recently faced the exact same issue with my app. UICollectionViewCell selection worked properly prior to iOS 8.3, subsequently I started to see some strange behaviour. Cells that were not actually selected would appear selected, other cells, seemingly at random could not be selected.
I had both custom setSelected and prepareForResuse methods implemented on a UICollectionViewCell subclass as such:
-(void)setSelected:(BOOL)selected
{
[super setSelected:selected];
if (selected)
{
[[self selectedIndicator] setHidden:NO];
}
else
{
[[self selectedIndicator] setHidden:YES];
}
}
-(void)prepareForReuse
{
[[self imageView] setImage:nil];
}
The prepareForReuse method simply reset an image view in the custom cell.
In my prepareForReuse method I did not make a call to [super prepareForReuse] (which according to the documentation does nothing by default). When I added the call to [super prepareForReuse] all selection worked as intended. Although Apple states the default implementation does nothing, they also recommend that super should be called. Following this recommendation solved my issue.
In iOS 10 I found that programmatically clearing a UICollectionView that had multiple-selection enabled was buggy when prefetching was enabled. And of course prefetch is on by default in iOS 10.

Resources