我想动态调整 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;
}
我只是想让它最初工作,因为它在滚动后工作,想法?
动态调整表格视图单元格内容的大小是一个众所周知的问题。虽然有一些笨拙的解决方法,但我相信正确的解决方案取决于您是否使用自动布局:
-
如果使用自动布局,请确保您的单元格图像视图具有宽度约束,然后您可以更改约束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
,然后调整图像视图的大小。看更改 UITableViewCell 的 imageView 的边界 https://stackoverflow.com/questions/3130804/changing-bounds-of-imageview-of-uitableviewcell.
无论您采用哪种方法,都使用UITableViewCell
子类消除了使用的需要viewForTag
构造,这使得视图控制器代码更加直观。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)