![](/img/trans.png)
[英]How can I keep an aspect ratio of UITableViewCell using Auto layout?
[英]how can UITableViewCell dynamically adapt to new image with aspect ratio retained?
我正在设计一个可以动态地将新图像加载到单元格中的表视图。
我的表视图层次结构是这样的:表视图-> myCustomCell->内容视图-> myCustomImageView。
我想要的是:在给定大小(例如300 * 50 )的屏幕上显示tableViewCells之后,用户可以点击一些单元格以显示特定大小的图像(例如600 * 600 )。 要更新单元格,我使用tableView.beginUpdates()和tableView.endUpdates() 。 然后,tabelViewCell的大小应更改为300 * 300 。
经过多次尝试,我面临以下问题:
如果我将imageView的contentmode设置为AspectFit,则tableViewCell的大小和imageView的大小都变为300 * 600 (实际图像为300 * 300 ),在单元格的顶部和底部区域有空白区域,如下所示:
如果将imageView的contentmode设置为AspectFill,则tableViewCell的大小和imageView的大小都变为300 * 600 (实际图像为600 * 600 ),左右两侧都被剪掉,像这样:
无论如何,要使tableViewCell最适合图像,同时保持宽高比? 非常感谢。
加载图像时,请计算图像的纵横比。
然后将约束添加到UIImageView以固定其宽高比。 宽高比约束一旦创建便无法更改,因此,每次更改图像时,您都必须删除任何现有的约束并添加新的约束。 就像是:
// Declare constraint as a property so you can remove it
@property NSLayoutConstraint *constraint;
// Remove previous constraint as multiplier property is read only.
if (self.constraint){
[self.imageView removeConstraint:self.constraint];
}
// Calculate aspect ration
CGFloat aspectRation = <insert calculation...>
// Add a new constraint for the new image setting the aspect ration
self.constraint = [NSLayoutConstraint constraintWithItem:self.imageView
attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual
toItem:self.imageView
attribute:NSLayoutAttributeWidth
multiplier:aspectRatio constant:0.0f];
// Add the new constraint.
[self.imageView addConstraint:constraint];
// View needs updated.
[self.contentView setNeedsLayout];
这将强制图像具有和计算出的宽高比。
为了使图像视图知道其宽度或高度(但不能同时知道两者的宽高比),因此必须为图像视图添加约束以满足显示需求。 例如,您可能希望使其与包含的视图具有相等的宽度,因此它始终会填充整个宽度,然后高度将根据长宽比等进行更改。这取决于您希望图像填充单元格的方式。
如果使用情节提要,您可能会发现为UIImageView提供宽高比会更容易,这样IB不会抱怨缺少约束。 按住CTRL键并将其拖动到单元头中,以便为该约束设置一个IBOutlet。 第一次,从UIImageView中删除IB版本。
希望这段代码对您有帮助
cimageView.contentMode = UIViewContentModeCenter;
if (imageView.bounds.size.width > ((UIImage*)imagesArray[i]).size.width && imageView.bounds.size.height > ((UIImage*)imagesArray[i]).size.height) {
imageView.contentMode = UIViewContentModeScaleAspectFit;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.