在UITableViewCell上根据其内容放置条件格式的正确方法?

时间:2013-02-26 13:19:57

标签: objective-c uitableview

我通过Core Data和NSFetchedResultsController引入一些对象,我试图根据它们的一个布尔属性对它们应用条件格式。如果它们被标记为Liked,我希望它们的文字颜色为蓝色,例如。

我发现的问题是,在滚动表格时,不仅仅是那些LikedYES的人正在着色。这也是一个常规模式,例如我向下滚动时每六个条目。我认为这与细胞排队和重复使用有关,但我不知道是什么。这是我的代码:

- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier forIndexPath: indexPath];

    Quote *thisQuote = [self.fetchedResultsController objectAtIndexPath: indexPath];

    cell.textLabel.numberOfLines = 4;
    cell.textLabel.font = [UIFont boldSystemFontOfSize: 12];
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.textLabel.text = [[self.fetchedResultsController objectAtIndexPath: indexPath] quote];

    if ([[thisQuote isLiked] boolValue]) {
        cell.textLabel.textColor = [UIColor blueColor];
    }

    return cell;
}

2 个答案:

答案 0 :(得分:2)

当您使用dequeueReusableCellWithIdentifier:时,您必须为每个单元格重置属性textColor:

if ([[thisQuote isLiked] boolValue]) {
    cell.textLabel.textColor = [UIColor blueColor];
}
else cell.textLabel.textColor = [UIColor blackColor];

答案 1 :(得分:0)

对于每第六个单元格,您可以随时执行:

if(indexPath.row % 6 == 0) {
    // Set blue color
}
else {
   // Set black color
}

或更容易:

cell.textLabel.textColor = (indexPath.row % 6 == 0) ? [UIColor blueColor] : [UIColor blackColor];