簡體   English   中英

在UITableViewCell中將UIImageView高度設置為與寬度成比例

[英]Set UIImageView height proportional to width in UITableViewCell

我正在嘗試創建一個UITableView ,其中每個單元格包含一個縱向或橫向UIImageView ,其中圖像在填充屏幕寬度時保持其縱橫比,如下所示:

|        |
|########|
|########|
|########|
|########|
|########|
|        |
|########|
|########|
|########|
|        |

我已經設置了autolayout約束來將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)
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM