2010-11-15 53 views
1

对于UITableViewController类的cellForRowAtIndexPath:方法,我使用下一个代码来显示包含UITextView的单元格。将单元格文本重新打印到UITableViewCell中

有时,当我滚动包含单元格的表格,然后滚动单元格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]; 

回答

5

UITableView重用其单元格来增加滚动性能。每当一个单元格被重用时,你正在为单元格添加一个新的文本视图(尽管已经存在)。

您应该将文本视图的创建(并将其添加到单元格)移动到if (cell == nil)块中。在该块内部,还可以给文本视图一个唯一的tag,并使用此tag属性从块外部访问文本视图。有关此模式的示例,请参阅Apple的表格视图示例代码,它正在被大量使用。

+0

谢谢Ole。它效果很好。 – 2010-11-15 16:21:37

相关问题