我正在尝试创建一个表格视图单元格,该单元格显示从Web下载的图像,并按比例缩小以适应设备的宽度。部分问题是我需要弄清楚如何在下载图像后调整单元格的大小。换句话说,我将在图像加载时设置默认高度,然后一旦图像加载,我想调整单元格的高度。我知道我可以将图像视图的内容模式设置为" aspect fit"一旦我指定了固定的宽度和高度,但我不确定如何以编程方式设置约束,以便高度保持灵活。
如何在代码中定义这些约束?
答案 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;
}