The problem is that I have implemented a table view with custom cell from storyboard. Each cell has a button as a selection button which mean whenever I press on a button , it image change. For example, if I press on the button with cell index=0, it image change correctly however when scrolling the table I found other buttons also changed their images! The problem is from the table index path and I spent a lot of time trying to fix it with no result. Any Solution?
Thank you
static NSString *simpleTableIdentifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:simpleTableIdentifier];
NSLog(@"index path inside cell = nil %i",(int)indexPath);
}
buttonObj=(UIButton *)[cell viewWithTag:40];
[buttonObj addTarget:self action:@selector(select:) forControlEvents:UIControlEventTouchDown];
return cell;
-(void) select:(id)sender{
UIButton *button=(UIButton *)sender;
UITableViewCell *clickedCell = (UITableViewCell*)[[sender superview] superview];
NSIndexPath *indexPathCell = [addFriendTableView indexPathForCell:clickedCell];
NSLog(@"indexPathCell %i",(int)indexPathCell.row);
Contacts* selectedContact = [contactsArray objectAtIndex:indexPathCell.row];
if([self image:button.imageView.image isEqualTo:[UIImage imageNamed:@"addFriend.png"]]==YES){
[button setImage:[UIImage imageNamed:@"addFriendPressed.png"] forState(UIControlStateNormal)];
[selectFriendsArray addObject:selectedContact];
counter++
}
else if( [self image:button.imageView.image isEqualTo:[UIImage imageNamed:@"addFriendPressed.png"]]==YES)
{
[button setImage:[UIImage imageNamed:@"addFriend.png"] forState:(UIControlStateNormal)];
counter--;
[selectFriendsArray removeObject:selectedContact];
}
This is down to cell reuse. When cells scroll off screen, they are put into a queue to be reused as other cells appear on screen. The dequeue method pulls them off this queue. Your problem is that the button image does not get reset when this happens, so if it had previously been changed, it wiil remain.
You need to add some code to your cellForRowAtIndexPath method to set the correct image based on its row.
Here what you are doing is getting same
UIButton
object for every cell. You need to create a separate button for every cell.Identify this
UIButton
object with unique tag and then select that cell for further.Create a tag for
UIButton
object. Put below line at top of your view controller class after#import
statmentsNow set unique tag for each object.
In your select method, check for that button tag.
Hope you will get idea, From this short explanation.