views:

871

answers:

3

I want to display a label showing a number in each cell of the tableview but the label is only visible when I click on a row (when the cell is highlited)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UILabel *label;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        label = [[UILabel alloc] initWithFrame:CGRectMake(200,10, 15, 15)];
        label.tag = 1;
        [cell.contentView addSubview:label];
        [label release];
    }
    else {
        label = (UILabel *)[cell viewWithTag:1];   
    }
    if (indexPath.row == 0) {
        cell.textLabel.text = @"Photos";
        label.text = [NSString stringWithFormat:@"%d",1];
    }
    return cell;
}
+1  A: 

When you update the textLabel property of a UITableViewCell, it lazily creates a UILabel and adds it to the cell's subviews. Usually you wouldn't use a combination of textLabel and adding subviews to contentView, but if you do you need to make sure the textLabel view isn't placed over the top of your contentView subviews.

Nathan de Vries
do you know how to make sure that the textLabel view isn't placed over the top of the contentView subviews?Cause it's actually the problem I have, the textlabel hides the label
Mathieu
You can use "-tableView:willDisplayCell:forRowAtIndexPath:" to rearrange the views of a cell prior to display.
Nathan de Vries
A: 

First, I assume this is targeting 3.0. Apple has changed how UITableViewCells are created in 3.0, and you should move over to that. -initWithFrame:reuseIdentifier: is deprecated.

That said, a likely problem is that the built-in textLabel is interfering with your added label, perhaps overlapping. You should look first at whether one of the new built-in styles meets your needs directly. If not I would recommend either just using your own views or only using the built-in views, possibly rearranging them. If you want to rearrange them, Apple suggests subclassing the cell and overloading -layoutSubviews. I also believe that -tableView:willDisplayCell:forRowAtIndexPath: is a good place to do final cell layout without subclassing.

Rob Napier
Thank you for this link, I'll study that tomorrow
Mathieu
A: 

I had the same problem and it was solved by setting the text for textlabel BEFORE adding the custom label as a subview.

...
cell.textLabel.text = @"X";
...
[cell.contentView addSubview:label]
Daniel