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;
}
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]
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.
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.
Using a custom UITableViewCell
gives you more control over the layout of a cell. Add custom views to the cell's contentView in the subclass and override the layoutSubviews
to set the order of the subviews:
- (void)layoutSubviews {
[super layoutSubviews];
[self.contentView bringSubviewToFront:self.yourCustomView];
}
来源:https://stackoverflow.com/questions/1430295/uitableview-subview-why-this-uilabel-is-not-visible