lloydsparkes
lloydsparkes

Reputation: 3164

iOS custom table view cell label resizing corruption

I am writing an iOS app for a client, the main view is a table view, and i fill the cells with text, much like most iOS twitter clients.

I have created a custom cell view with 3 labels, and i fill these labels with the texts. One of the labels needs to resize automatically depending on the amount of text there is (maximum of 140 characters).

This works fine until i scroll up/down the list when the text either extends to a single full line (like the label has expanded) OR only takes up part of the space so it ends up deeper and overflowing into other labels (i do have "Clip Subviews" enabled as per another similar SO question)

So when the table and its data is first loaded the screen looks like:

before scrolling http://lloydsparkes.co.uk/files/iOS-BeforeScrolling.png

And after a bit of scrolling it looks like:

after scrolling http://lloydsparkes.co.uk/files/iOS-AfterScrolling.png

So it seems that the label is resizing during the scrolling (maybe due to the same cell being reused?) and not resizing back to the correct size.

My code for filling a cell is:

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

static NSString *myID = @"customCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:myID];

if(cell == NULL) {

    [[NSBundle mainBundle] loadNibNamed:@"CustomCellView" owner:self options:nil];

    cell = customCell;
    self.customCell = nil;
}

Post *p = [posts objectAtIndex:indexPath.row];

UILabel *label = (UILabel*)[cell viewWithTag:15];
label.text = p.Name;

label = (UILabel*)[cell viewWithTag:10];
label.text = p.Text;
[label sizeToFit];

label = (UILabel*)[cell viewWithTag:20];
label.text = [p Source];

//[cell layoutSubviews];

return cell;
}

So what i am asking is, what is causing this problem? and how can it be solved?

Upvotes: 1

Views: 3425

Answers (1)

Felipe Sabino
Felipe Sabino

Reputation: 18215

The sizeToFit method might be behaving in a weird way because the UILabel frame is changed every time cellForRowAtIndexPath is called.

One thing you can try is setting the frame of the label object back to the original size (the valeu set in the NIB file) right before calling sizeToFit

[label setFrame:CGRectMake(0.0f, 0.0f, 100.0f, 50.0f)];    
[label sizeToFit];

Upvotes: 7

Related Questions