Ios 在UITableViewCell中设置与宽度成比例的UIImageView高度
我试图制作一个Ios 在UITableViewCell中设置与宽度成比例的UIImageView高度,ios,uitableview,uiimageview,Ios,Uitableview,Uiimageview,我试图制作一个UITableView,其中每个单元格包含纵向或横向UIImageView,其中图像在填充屏幕宽度时保持其纵横比,如下所示: | | |########| |########| |########| |########| |########| | | |########| |########| |########| | | 我已经设置了自动布局约束,将UIImageView的边缘附加到表视图单元格的contentView。这适用于宽度,但
UITableView
,其中每个单元格包含纵向或横向UIImageView
,其中图像在填充屏幕宽度时保持其纵横比,如下所示:
| |
|########|
|########|
|########|
|########|
|########|
| |
|########|
|########|
|########|
| |
我已经设置了自动布局约束,将UIImageView
的边缘附加到表视图单元格的contentView
。这适用于宽度,但高度不是我想要的-它总是扩展到基础图像的完整高度
我在表视图中有以下设置:
self.tableView.estimatedRowHeight = 100.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;
在构建单元时,我试图计算必要的高度,以便更改UIImageView
的帧(或高度约束):
let cell = tableView.dequeueReusableCellWithIdentifier("activityPostCell", forIndexPath: indexPath) as UITableViewCell
let image = UIImage(named: "my-image.jpg")
let aspectRatio = image!.size.height / image!.size.width
let imageView = cell.viewWithTag(15) as UIImageView
let imageViewHeight = aspectRatio * imageView.frame.width
这里的问题是,我得到的imageView.frame
是在布局发生之前,所以我没有计算正确的高度
我这样做对吗?是否有一种简单的方法来设置
UIImageView
的纵横比以匹配它包含的图像?提前感谢。根据@Wain的建议,添加纵横比约束解决了问题:
let image = UIImage(named: "my-image.jpg")
let aspectRatio = image!.size.height / image!.size.width
let imageView = cell.viewWithTag(15) as UIImageView
imageView.addConstraint(NSLayoutConstraint(
item: imageView,
attribute: NSLayoutAttribute.Height,
relatedBy: NSLayoutRelation.Equal,
toItem: imageView,
attribute: NSLayoutAttribute.Width,
multiplier: aspectRatio,
constant: 0)
)
你看过在图像视图上使用纵横比约束吗?是的,这就成功了,谢谢。我将添加我的解决方案作为答案。如何调用uiviewcontroller刷新其内容?例如在uitableviewcell上?