iosobjective-cuitableviewuilabelsizetofit

UITableView with UILabel SizeToFit get mess when Scrolling


Hi everyone I have problem with my tableview, i make Cell with uilabel with SizeToFit and then calculate the UILabel Height for set the cell Height everything work well except when i scrolling my tableView the text get weird like one char per line:

My TableViewVell Method is:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}


UILabel *label = (UILabel *)[cell viewWithTag:1];
label.text = [someArray objectAtIndex:indexPath.row];
// Set the UILabel to fit my text;
messageLabel.lineBreakMode = UILineBreakModeWordWrap;
messageLabel.numberOfLines = 0;
[messageLabel sizeToFit];


return cell;   
}

The Cell Height stay in the correct Size the problem only with the UILabel ... this the result when i load the view:

First screenshot

And this is after i start scroll the TableView:

Second screenshot

Any Help???


Solution

  • you should probably subclass your cell and clean the UILabel on

     override func prepareForReuse() {
        super.prepareForReuse()
        self.label.text = nil
    }