I am developing an app in which, the image of the UIButton in UITableViewCell should change on click and I have done this in a custom cell. Right now, I am able to change the image of the button but it is also changing the image of few other buttons too as I scroll down (as cellForRowAtIndexPath:
is called on scrolling).
Here is the code.
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
_cell = (ListTableViewCell *)[self.tblList dequeueReusableCellWithIdentifier:@"listTableViewCell"];
if (_cell == nil) {
_cell = [[ListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"listTableViewCell"];
} else {
_cell.imgIcon.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",[_arrImages objectAtIndex:indexPath.row]]];
_cell.lblList.text = [NSString stringWithFormat:@"%@",[_arrNames objectAtIndex:indexPath.row]];
_cell.btnList.tag = indexPath.row;
if (_cell.btnList.tag == indexPath.row) {
[_cell.btnList addTarget:self action:@selector(btnPressedMethodCall:) forControlEvents:UIControlEventTouchUpInside];
}
}
return _cell;
}
- (void) btnPressedMethodCall:(UIButton*)sender {
if ([sender isSelected]) {
[sender setImage:[UIImage imageNamed:@"red_image.png"] forState:UIControlStateSelected];
[sender setSelected:NO];
} else {
[sender setImage:[UIImage imageNamed:@"black_image.png"] forState:UIControlStateNormal];
[sender setSelected:YES];
}
}
Could someone please tell how this problem can be solved. Any help is appreciated thanks.