在cellForRowAtIndexPath:
类的UITableViewController
方法中,我使用下一个代码来显示包含UITextView
的单元格。
有时当我滚动包含单元格的表格然后滚动单元格UITextView
时,它会显示重新打印的单元格文本(就好像有两个UITextView
个对象而不是一个,进入细胞)。
我该怎么做才能解决这个问题?
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.contentView.bounds = CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height);
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UITextView *textView = [[UITextView alloc] initWithFrame:cell.contentView.bounds];
textView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
textView.editable = NO;
textView.scrollEnabled = YES;
textView.backgroundColor = [UIColor clearColor];
textView.font = [UIFont fontWithName:@"Helvetica" size:14.0];
textView.text = self.description;
[cell.contentView addSubview:textView];
[textView release];
答案 0 :(得分:5)
UITableView重用其单元格以提高滚动性能。无论何时重复使用单元格,您都要向单元格添加一个新的文本视图(尽管已经存在一个)。
您应该将文本视图的创建(并将其添加到单元格)移动到if (cell == nil)
块中。在此块中,还为文本视图提供唯一的tag
,并使用此tag
属性从块外部访问文本视图。有关此模式的示例,请参阅Apple的表视图示例代码,它正在被大量使用。