yong ho
yong ho

Reputation: 4042

Why scroll UITableView up and down mess up with me UIButton title color which I have changed

I have added a UIButton to my table view cell, and when I tap on the button, it sets the button's titleColor to gray, and set my datasource's watched property to true, default is false. So, when a row's watched equal to true, the UIButton's title should be gray, if not, it should be the default color, blue. As you can see below, everything works perfectly, but If I tap a UIButton, the text color changes to gray, and it's datasource gets changed too. But If I scroll my tableview up and down, the some other cell's button text color changes to gray too.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    EposideCell *cell = (EposideCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[EposideCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    [cell.number addTarget:self action:@selector(eposideWatched:) forControlEvents:UIControlEventTouchUpInside];
    E *eposide = self.eposides[indexPath.section][@"eposides"][indexPath.row];
    cell.eposideTitle.text = eposide.title;
    [cell.number setTitle:[eposide.episode stringValue] forState:UIControlStateNormal];
    return cell;
}

- (void)eposideWatched:(UIButton *)sender
{
    CGPoint buttonPoint = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPoint];
    EposideCell *cell = (EposideCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    //ignore a lot of core data fetch request code
    findE.watched = [NSNumber numberWithBool:![findE.watched boolValue]];

    [self.managedObjectContext dct_saveWithCompletionHandler:^(BOOL success, NSError *error) {
        if (success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [cell.number setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                [self.tableView reloadData];
            });
        }
    }];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    EposideCell *eCell = (EposideCell *)cell;
    E *eposide = self.eposides[indexPath.section][@"eposides"][indexPath.row];
    if ([eposide.watched boolValue]) {
        [eCell.number setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    }
}

Upvotes: 1

Views: 540

Answers (1)

johnMa
johnMa

Reputation: 3311

if ([eposide.watched boolValue]) {
    [eCell.number setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
}else{
    [eCell.number setTitleColor:yourOriginColor forState:UIControlStateNormal];
}

You have to set color back to your origin color, because tableview will reuse the greyColor cell.

Upvotes: 2

Related Questions