views:

1421

answers:

2

Hi everyone,

I am trying to customize the font of a uitableviewcell using the following code for when the tableview is populated.

- (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;
}

For the life of me I don't know why it wont change the font! Also the above code works fine if I hard code in what the cell text is such as cell.textLabel.text = @"TEST";

Any suggestions? Thanks!

+4  A: 

First, you should autorelease your cell. You are leaking memory like crazy presently.

Second, you should update the font in tableView:willDisplayCellForRow:atIndexPath:. If you are using a standard table view, it will make changes to your cells (at random times) and you will need to do things like font changes, background color, etc in the tableView:willDisplayCellForRow:atIndexPath: instead of in the data source method.

See also this thread: http://stackoverflow.com/questions/1890265/what-is-uitableviewdelegate-willdisplaycellforrowatindexpath-for

Jason Coco
Could you please elaborate on the methods where I should change it? Thanks!
Phillip Whisenhunt
Nevermind, just got it.
Phillip Whisenhunt
A: 

Just you can try with following code.

-(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.textColor = [UIColor colorWithRed:154.0/255.0 green:14.0/255.0 blue:2.0/255.0 alpha:1]; cell.font = [UIFont systemFontOfSize:12.0]; return cell; }

jfalexvijay