sizeToFit not working like we expecting

170 views Asked by At

I face a strange problem with an UILabel in UITableView. I have a label inside of a cell and I want use sizeToFit for it because I will move a UIImageView right after text.

The problem is that the first time sizeToFit does not work as expected but after a little scroll my code is works perfectly.

In cellForRow:

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

if (cell==nil) {
    cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}

UILabel *lbl = [cell.contentView viewWithTag:1];
lbl.text = [self.word1 objectAtIndex:self.word1.count - indexPath.row - 1];

CGRect rct = lbl.frame;
rct.size.width = 300;
lbl.frame = rct;
[lbl sizeToFit];
UIView *view = [cell.contentView viewWithTag:2];
rct = view.frame;
rct.origin.x = CGRectGetMaxX(lbl.frame) + 8;
view.frame = rct;


return cell;

And two pictures to better understand:

First time, when size to fit works strange

After scroll, when the new cell are created correctly. After scroll, when the new cells are created correctly.

0

There are 0 answers