具有UIImage的UITableViewCell,宽度在初始显示的单元格上不更新

我想dynamic调整一个UITableViewCell里面的UIImage的宽度,我使用故事板来deviseUITableViewCell,我只是添加了一个标签和一个图像,属性得到正确更新,我甚至加载的值将宽度放入标签以显示它是正确的值,对于图像,我正在加载一个我想重复的背景图像,但是图像最初不会更新宽度,如果我上下滚动,图像如预期的那样显示,这里是cellForRowAtIndexPath的代码,我也试着把代码放在willDisplayCell方法上,结果相同

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mycustomcell"]; int r = [[data objectAtIndex:indexPath.row] intValue]; UIImageView *img = (UIImageView *)[cell viewWithTag:2]; img.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"some_img" ofType:@"png"]]]; CGRect frame = img.frame; frame.size.width = r*16; img.frame = frame; int n = img.frame.size.width; UILabel *label = (UILabel *)[cell viewWithTag:1]; label.text = [NSString stringWithFormat:@"custom %d", n]; [cell setNeedsDisplay]; return cell; } 

我只是希望这个工作起初,因为它滚动后,思想?

桌面单元内容的dynamicresize是一个众所周知的问题。 虽然有一些可行的解决方法,但我相信适当的解决scheme取决于您是否使用自动布局:

  • 如果使用自动布局,请确保您的单元格的图像视图具有宽度约束,然后您可以更改约束的constant

     for (NSLayoutConstraint *constraint in img.constraints) { if (constraint.firstAttribute == NSLayoutAttributeWidth) constraint.constant = r*16; } 

    坦率地说,我宁愿使用一个自定义的UITableViewCell子类,并有宽度约束的IBOutlet (例如imageWidthConstraint ),并且它不必通过约束枚举来find正确的约束,而且可以简单地:

     cell.imageWidthConstraint.constant = r*16; 
  • 如果不使用自动布局,则应UITableViewCell子类,将其用于您的单元格原型的基类,然后重写layoutSubviews ,然后调整图像视图的大小。 请参阅更改UITableViewCell的imageView边界 。

无论采用哪种方法,使用UITableViewCell子类viewForTag需要使用viewForTag结构,这使视图控制器代码更加直观。

呃,删除Auto Layout修复了这个问题