【发布时间】:2014-03-05 04:10:45
【问题描述】:
我提供了一个包含一些文本的单元格和一个图像的 URL。
使用imageFromURL: 方法显示图像的 ImageView 是一个自定义类,它在内部查看自己的大小并将查询附加到 URL,例如:
.com/img.png?ver=200&hor=500
服务器然后计算出返回哪个尺寸的图像以获得最佳结果。
这意味着我需要 AutoLayout 在除文本之外的任何内容之前对 imageView 进行布局。在我保证 imageView 有它的最终大小后,我调用 imageWithURL: 方法。
我构建的自动布局填满了我的 textLabel,并且由于单元格高度是固定的,因此它决定了为图像留下的内容。 (一些抗压性、最小尺寸等都在其中 - 这一切都有效,我从下面的代码中省略了它)。
- (id) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
/*
stuff that goes into making the cell ready
.
.
.
*/
[self setNeedsUpdateConstraints];
return self;
}
- (void)updateConstraints
{
/*
first set the different constraints
.
.
.
then call super
*/
[super updateConstraints];
}
- (void) updateCellWithText:(NSString*) text andImageURL:(NSURL*) imgURL
{
self.textLabel.text = text;
[self.imageView setImageWithURL:imgURL];
//calling setNeedsUpdateConstraints here won't help much as there is still not a correct size
}
- (void) layoutSubviews
{
[super layoutSubviews];
NSLog(@"%@", NSStringFromCGSize(self.imageView.frame.size));
}
我从layoutSubviews: 记录的是:
- {0,0} //第一次
- {320,498} //OK 现在看起来正确 - 可以调用 imageWithURL: now
- {320,498} //可能是一个额外的用于计算单元格或表格视图 身高?
我的目标是弄清楚我们何时完成布局,然后我可以调用我的 setImageWithURL: 并为 imageView 提供正确的大小。
layoutSubviews 似乎是我唯一可以挂钩此信息的地方 - 但我真的觉得将这样的代码添加到 layoutSubviews 并将我的数据更新混合到我的布局代码中感到不舒服:
if (_imageView.frame.size.width == 0)
[_imageView setImageWithURL:_propertyWithURL];
同样从上面的日志中,这会导致我的图像被设置 2 次,因为 layoutSubviews 被多次调用。
所以,希望有人可以帮助我正确确定这些调用的顺序,或者建议一种不同的方法来实现结果。
提前致谢。
【问题讨论】:
-
我遇到了完全相同的问题。你最后是怎么解决的?
标签: ios uitableview autolayout