我想在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;
}
我只是想让它最初起作用,因为它在滚动之后起作用,想法?
答案 0 :(得分:7)
tableview单元格内容的动态调整大小是一个众所周知的问题。虽然有kludgy变通方法,但我认为正确的解决方案取决于您是否使用autolayout:
如果使用自动布局,请确保单元格的图像视图具有宽度约束,然后您可以更改约束的constant
:
for (NSLayoutConstraint *constraint in img.constraints)
{
if (constraint.firstAttribute == NSLayoutAttributeWidth)
constraint.constant = r*16;
}
坦率地说,我宁愿使用自定义UITableViewCell
子类,并为宽度约束设置IBOutlet
(例如imageWidthConstraint
),这样就不必枚举通过约束找到合适的,你可以简单地说:
cell.imageWidthConstraint.constant = r*16;
如果不使用自动布局,则应将UITableViewCell
子类化,将其用于单元原型的基类,然后覆盖layoutSubviews
,并在那里调整图像视图的大小。请参阅Changing bounds of imageView of UITableViewCell。
无论采用哪种方法,使用UITableViewCell
子类都不需要使用viewForTag
构造,这使得视图控制器代码更加直观。
答案 1 :(得分:1)
argh,删除自动布局修复了问题