2015-12-17 20 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; 
} 
相关问题