I am having a list displaying a name and a button titled as "Follow". When I tap on the button title should change to "UnFollow". If I tap on the button again the title should again change to "Follow". This is working fine, but when I am scrolling the table the title of the other cells are also changing due to cell reuse.
The code is as follows:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"AuthorsListCell";
AuthorsListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
dic_eachAuthor = [[_arr_authors objectAtIndex:indexPath.row] mutableCopy];
cell.lbl_authorName.text = [dic_eachAuthor objectForKey:@"name"];
cell.btn_followOrUnfollow.tag = indexPath.row;
if([dic_eachAuthor valueForKey:@"follow"]){
[cell.btn_followOrUnfollow setTitle:@"UnFollow" forState:UIControlStateNormal];
}
else{
[cell.btn_followOrUnfollow setTitle:@"Follow" forState:UIControlStateNormal];
}
// action button method declarations
[cell.btn_followOrUnfollow addTarget:self action:@selector(followOrUnfollow:) forControlEvents:UIControlEventTouchUpInside];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
-(void)followOrUnfollow:(UIButton *)sender
{
if ([sender.titleLabel.text isEqualToString:@"Follow"]) {
[sender setTitle:@"UnFollow" forState:UIControlStateNormal];
[dic_eachAuthor setValue:@"1" forKey:@"follow"];
}
else if ([sender.titleLabel.text isEqualToString:@"UnFollow"]) {
[sender setTitle:@"Follow" forState:UIControlStateNormal];
[dic_eachAuthor setValue:nil forKey:@"follow"];
}
}
Please suggest something to prevent the cell reuse.
You are missing something here, try this :