当我重新使用它时,如何完全清除单元格?
当我调用[table reloaddata];
单元格会重新绘制新的数据,但是我的UILabel会因为被拖到旧的UILabel上而变得混乱起来,所以一团糟。
static NSString* PlaceholderCellIdentifier = @"PlaceholderCell"; UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:PlaceholderCellIdentifier] autorelease]; cell.detailTextLabel.textAlignment = UITextAlignmentCenter; cell.selectionStyle = UITableViewCellSelectionStyleNone; cell.contentView.backgroundColor = [UIColor clearColor]; }
是我的初始细胞。
我像这样添加一个UILabel
UILabel *theDateLabel = [[UILabel alloc] initWithFrame:CGRectMake(140, 35,140, 20)]; [theDateLabel setBackgroundColor:[UIColor clearColor]]; [theDateLabel setTextColor:[UIColor lightGrayColor]]; [theDateLabel setText:[dateFormatter stringFromDate:theDate]]; [theDateLabel setFont:[UIFont fontWithName:@"TrebuchetMS-Bold" size:15]]; [cell addSubview:theDateLabel]; [theDateLabel release];
单元格中还有更多的标签,同样的东西。
我想要发生的是旧的标签从细胞中消失,使它们不再可见。
您不应该添加theDateLabel
作为cell
的子视图。 你应该添加它作为cell.contentView
的子视图。
正如yuji所build议的,实现这一点的一种方式是为每个自定义子视图创build一个具有属性的UITableViewCell
的子类。 这样,你可以很容易地获得一个重用单元格的date标签来设置新行的文本。
另一个常见的方法是使用每个UIView
具有的tag
属性。 例如:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString* PlaceholderCellIdentifier = @"PlaceholderCell"; static const int DateLabelTag = 1; UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier]; if (!cell) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:PlaceholderCellIdentifier] autorelease]; UILabel *theDateLabel = [[UILabel alloc] initWithFrame:CGRectMake(140, 35,140, 20)]; theDateLabel.tag = DateLabelTag; theDateLabel.backgroundColor = [UIColor clearColor]; theDateLabel.textColor = [UIColor lightGrayColor]; theDateLabel.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:15]; [cell.contentView addSubview:theDateLabel]; [theDateLabel release]; } NSDate *theDate = [self dateForRowAtIndexPath:indexPath]; UILabel *theDateLabel = [cell.contentView viewWithTag:DateLabelTag]; theDateLabel.text = [dateFormatter stringFromDate:theDate]; return cell; }
虽然理查德的解决scheme将工作,如果您的单元格有任何其他子视图,他们也将被删除。 另外,每次绘制单元格时分配和初始化子视图不一定是最佳的。
这里的标准解决scheme是用属性@dateLabel
创buildUITableViewCell
的子类(对其他标签也是如此)。 然后,当你初始化一个单元格时,如果它没有@dateLabel
,你可以给它一个新的,否则你只需要设置它的文本。