繁体   English   中英

如何更改表格视图单元格文本标签的颜色

[英]How to change table view cell text label color

我在这里进行了很多搜索,发现很多人告诉我将代码放入if (cell == nil) ,我做到了,但是没有用。

我的代码:

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

    cell.textLabel.text = [listaMaterias objectAtIndex:indexPath.row];

    if (cell == nil) {

        cell.textLabel.textColor = [UIColor colorWithRed:17/255 green:112/255 blue:1/255 alpha:1];
    }

    return cell;
}

在创建UIColor时,您正在使用整数除法。 17/255 =0。您要使用浮点除法:[UIColor colorWithRed:17.0f / 255.0f绿色:112.0f / 255.0f蓝色:1.0f / 255.0f alpha:1.0f]。

顺便说一句,该(cell == nil)检查不是必需的,因为在nil上调用方法是合法的,它们只是不做任何事情(如果返回对象,则将返回nil)。 因此,“((nil).textLabel”)的计算结果为nil,而“(nil).textColor =“(即变为“ [nil setTextColor:]]”)立即返回。

dequeueReusableCellWithIdentifier:forIndexPath:始终返回一个有效的单元格,因此该单元格永远不会nil并且该代码也永远不会执行。 您之前遵循的建议适用于initWithStyle:reuseIdentifier:的使用,并且可能返回nil ,因此需要在cell == nil块中创建cell == nil

只要将颜色创建代码更改为@Sean Cier指出的内容,就可以直接调用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM