uitableview subview : why this uilabel is not visible?

匿名 (未验证) 提交于 2019-12-03 02:29:01

问题:

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:

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] 


回答2:

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.



回答3:

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.



回答4:

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!