2015-12-17 19 views
0

我正在嘗試創建單個表格視圖單元格,該單元格顯示圖像,從網頁下載並縮小到適合設備寬度。部分問題是我需要弄清楚下載圖像後如何調整單元格的大小。換句話說,我將在圖像加載時設置默認高度,然後一旦圖像加載完成,我想調整單元格的高度。我知道我可以將圖像視圖的內容模式設置爲「縱橫比」,只要我指定了固定的寬度和高度,但我不確定如何以編程方式設置約束,以便高度可以保持靈活。如何以編程方式將UIImageView縮放到固定寬度和靈活高度?

如何在代碼中定義這些約束?

+0

如果我理解正確的話,你想的細胞高度的圖像的高度? –

+0

不一定是圖像的高度,但與圖像縮小後的UIImageView高度相同。 – Andrew

+0

圖像視圖的高度如何改變? –

回答

1

使用此代碼來調整圖像大小後,圖像已被下載:

//example 
//UIImageView *yourImageView = [self imageWithImage:yourDownloadedImage scaledToWidth:CGRectGetWidth(self.view.frame)] 


- (UIImage*)imageWithImage: (UIImage*) sourceImage scaledToWidth:(float)i_width{ 
float oldWidth = sourceImage.size.width; 

if (oldWidth <= self.view.frame.size.width) { 
    return sourceImage; // remove this line if you want the image width follow your screen width 
} 
float scaleFactor = i_width/oldWidth; 
float newHeight = sourceImage.size.height * scaleFactor; 

UIGraphicsBeginImageContext(CGSizeMake(i_width, newHeight)); 
[sourceImage drawInRect:CGRectMake(0, 0, i_width, newHeight)]; 
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
return newImage; 
} 

然後設置你的身高與此:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath]; // i'm using static cell so i call this 
    return [self calculateHeightForConfiguredSizingCell:cell]; 
} 

- (CGFloat)calculateHeightForConfiguredSizingCell:(UITableViewCell *)sizingCell { 
[sizingCell layoutIfNeeded]; 

CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; 
return size.height; 
} 
相關問題