iosobjective-cuitableviewsizetofit

UItableviewcontroller SizeToFit not working on UILabel field


Hi I am using sizetofit on my UILabel field, it works fine when I load the tableview controller, but then starts cutting of letters and wrapping to another line when I scroll up and down. Here is the code I use in CellForRowAtIndexPath:

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

    // Configure the cell...

    // Load and display subject photo image
    UIImageView *subjectImageView = (UIImageView *)[cell viewWithTag:200];
    subjectImageView.image = [UIImage imageNamed:subjectImages[indexPath.row]];


    // Load and display subject label
    UILabel *subjectLabel = (UILabel *)[cell viewWithTag:201];
    subjectLabel.text = [subjectItems objectAtIndex:indexPath.row];
    [subjectLabel sizeToFit];// call this to fit size of the label according to text



    return cell;
}

And here is a screen shot of my tableviewcontroller originaly loaded:

enter image description here

And here after scrolling up and down you can see the descriptions have been cut

enter image description here

Thanks for any help you can give to solve this.

Cheers

Carson


Solution

  • Using sizeToFit for UILabel can cause a mess like this in UITableView with reusing cells. One of solutions I can think of is to set the width of the frame for your label width before you call sizeToFit and you have to do this every time you assign text to the label. It should look something like this:

    CGRect frame = subjectLabel.frame;
    frame.size.width = 100.0; //try to adjust this value 
    subjectLabel.frame = frame;
    [subjectLabel sizeToFit];