Into the cellForRowAtIndexPath: method of an UITableViewController class I am using the next code to show a cell that contains an UITextView.
Sometimes when I scroll the table that contains the cell and then I scroll the cell UITextView, it shows the cell text reprinted (as if there were two UITextView objects, instead of one, into the cell).
What can I do to solve this problem?
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];
UITableView reuses its cells to increase scrolling performance. Whenever a cell is being reused, you are adding a new text view to the cell (although one is already there).
You should move the creation of the text view (and adding it to the cell) into the
if (cell == nil)block. Inside this block, also give the text view a uniquetagand use thistagproperty to access the text view from outside the block. See Apple’s table view sample code for examples of this pattern, it is being used a lot.