UITableViewCell字体未改变

18

我正在尝试使用以下代码在表格视图填充时自定义UITableViewCell的字体。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *MyIdentifier = @"MyIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) 
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
    }

    // Set up the cell  
    int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];   
    NSString *temp = [[NSString alloc] initWithString:[[stories objectAtIndex: storyIndex] objectForKey: @"title"]];
    cell.textLabel.text = temp;
    [[cell textLabel] setTextColor:[UIColor colorWithRed:154.0/255.0 green:14.0/255.0 blue:2.0/255.0 alpha:1]];
    [[cell textLabel] setFont:[UIFont systemFontOfSize:12.0]];  

    return cell;
}

我真的不知道为什么它不会改变字体!如果我像这样硬编码单元格文本,cell.textLabel.text = @"TEST"; 上面的代码就可以正常工作。

有什么建议吗?谢谢!

6个回答

29

首先,您应该自动释放单元格。目前您正在泄漏内存。

其次,您应该在tableView:willDisplayCellForRow:atIndexPath:中更新字体。如果您正在使用标准表视图,它将随机更改单元格(在某些时候),因此您需要在tableView:willDisplayCellForRow:atIndexPath:中进行诸如字体更改、背景颜色等操作,而不是在数据源方法中进行操作。

另请参阅此线程:什么是 - [UITableViewDelegate willDisplayCell:forRowAtIndexPath:]?


请问您能详细说明一下我应该更改的方法吗?谢谢! - Phillip Whisenhunt

8

@Jason Coco:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
}

4

你可以尝试使用以下代码。


-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellString = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellString];
    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellString];
    }
    cell.textLabel.text = values;
    cell.textLabel.textColor = [UIColor colorWithRed:154.0/255.0 green:14.0/255.0 blue:2.0/255.0 alpha:1];
    cell.textLabel.font = [UIFont systemFontOfSize:12.0];
    return cell;
}

尝试使用cell.textLabel.font或cell.detailTextLabel.font。 - jfalexvijay

3

请尝试,

cell.textLabel.font = [UIFont systemFontOfSize:12.0];
cell.detailTextLabel.font = [UIFont systemFontOfSize:10.0];

1

willDisplayCell:forRowAtIndexPath:可以用于修改单元格的背景颜色、内容视图等,但不能修改textlabel和detailtextlabel的backgroundColor属性。

在上述方法中进行这些修改始终是一个好习惯。


-2
非常简单,`

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{

   cell.textLabel.textColor = [UIColor grayColor]; //redColor greenColor etc.
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接