Search code examples
iosuitableviewtextlabel

uitableview cells blank but correct text in console


i Have two issues

1) if i dont comment out the if(cell==nil) then the text labels dont show in one of my tableviews on my phone.

2) the other i have the same problem, but if i have this commented out the text doesn't appear to change. However if i

 NSLog(@"did select  and the text is %@",[tableView cellForRowAtIndexPath:indexPath].textLabel.text);

I get the output "did select and the text is 'site number 1 '" which is what i want, however the text i see on the phone screen is not what i see in the console can anyone help? here is my code:

my cell identifier in the attributes inspector of the tableview is "selcell"

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    int row=indexPath.row;
    NSLog(@"number in sites is %d cell for row %@",[sites count],[sites objectAtIndex:row]);

    static NSString *CellIdentifier = @"selcell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
   // if(cell==nil)
   // {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.textLabel.text=[NSString stringWithFormat:@"site number %@",[sites objectAtIndex:row]];
   // }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"did select  and the text is %@",[tableView cellForRowAtIndexPath:indexPath].textLabel.text);
    [self.delegate didSelectSite:[sites objectAtIndex:indexPath.row]];
}

Solution

  • In the table view there is this concept of reusing the cells. And the if block cell==nil is only run when there is no cell to be reused by the table view.

    So you still need to set the title for the cell no matter whether you are using a newly allocated cell or reused cell.

    Take out the following line from the if block and see if it works:

        cell.textLabel.text=[NSString stringWithFormat:@"site number %@",[sites objectAtIndex:row]];