簡體   English   中英

UITableViewCell如何在保留寬高比的情況下動態適應新圖像?

[英]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 ),在單元格的頂部和底部區域有空白區域,如下所示: contentmode = AspectFit

如果將imageView的contentmode設置為AspectFill,則tableViewCell的大小和imageView的大小都變為300 * 600 (實際圖像為600 * 600 ),左右兩側都被剪掉,像這樣: contentmode = AspectFill

無論如何,要使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.

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