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

Bla*_*erX 3 xcode objective-c storyboard uitableview ios

我想在UITableViewCell里面动态调整UIImage的宽度,我正在使用故事板来设计UITableViewCell,我只是添加了一个标签和一个图像,属性得到了正确的更新,我甚至加载了值标签中的宽度显示它是正确的值,对于图像,我正在加载我想要重复的背景图像,但是如果我向上和向下滚动图像,图像将不会最初更新宽度如预期所示,这里是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;
}
Run Code Online (Sandbox Code Playgroud)

我只是想让它最初工作,因为它在滚动后起作用,想法?

Rob*_*Rob 7

tableview单元的内容的动态调整大小是众所周知的问题.虽然有kludgy解决方法,但我认为正确的解决方案取决于您是否使用autolayout:

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

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

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

    cell.imageWidthConstraint.constant = r*16;
    
    Run Code Online (Sandbox Code Playgroud)
  • 如果不使用自动布局,则应该子类化UITableViewCell,将其用于单元原型的基类,然后覆盖layoutSubviews,并在那里调整图像视图的大小.请参阅更改UITableViewCell的imageView边界.

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

  • 这应该是接受的答案,而不是从原始海报中删除自动布局. (2认同)