iOS:UIImageView随着UITableView.rowHeight的变化而变化,如何避免?

时间:2014-08-31 00:08:36

标签: ios objective-c uitableview uiimageview

这是一个n00b问题,我在尝试构建应用时正在学习iOS

我需要在UITableViewCell上显示图片,标签。以下代码为我做了

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    cell.imageView.image = [self getImageNameForRow:indexPath.row];
    cell.textLabel.text = self.features[(NSUInteger) indexPath.row];
    cell.imageView.contentMode = UIViewContentModeScaleAspectFit;

    return cell;
}

问题在于图像尺寸比我预期的要大。所以我试着将行的高度增加为

self.tableView.rowHeight = 80;

然后图像也会扩大。

enter image description here

如何在增加(或更改)行的大小时保持图像大小固定?

2 个答案:

答案 0 :(得分:2)

问题是您使用的是默认的表格视图单元格样式。该样式带有内置textLabelimageView,后者是带有约束的UIImageView,因此可以调整其大小以填充单元格的高度。但你也说过

 cell.imageView.contentMode = UIViewContentModeScaleAspectFit

这意味着随着图像视图的增长,图像随之增长 - 正是您所看到的。

正如我解释here一样,解决方案是将图片缩小到您想要的实际尺寸 - 并将图片视图的contentMode设置为center。像这样:

UIImage* im = [self getImageNameForRow:indexPath.row];
UIGraphicsBeginImageContextWithOptions(CGSizeMake(36,36), YES, 0);
[im drawInRect:CGRectMake(0,0,36,36)];
UIImage* im2 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
cell.imageView.image = im2;
cell.imageView.contentMode = UIViewContentModeCenter;

36,36更改为您实际需要的尺寸。

无论如何,这是一种很好的做法。以比实际显示所需的更大的尺寸保持图像是一种可怕的记忆浪费(浪费的存储量以指数方式增长,因为面积在单个维度的平方的量级上)。所以你应该总是将图像大小缩小到实际的显示尺寸。 Stack Overflow上有很多代码,显示了许多其他方法。

答案 1 :(得分:1)

我相信你的主要问题是图片太大了。如果图像只有40x40,它将显示为tableViewCell高度的一半(当它为80时)。 IIRC UIImageView,UITableViewCell延伸到单元格的高度,如果它们足够大,图像将始终填充它。

你可以做的三件事:

1)将图像尺寸缩小到您想要的尺寸。

2)手动更改imageView的框架,如下所示:

cell.imageView.image = [self getImageNameForRow:indexPath.row];
CGPoint center = cell.imageView.center;
CGRect frame = cell.imageView.frame;
frame.size.width = 40;
frame.size.height = 40;
cell.imageView.frame = frame;
cell.imageView.center = center;

我不完全确定你是否需要缓存中心并在帧更改后重新设置它(UITableViewCell可能会自动执行此操作)。

3)创建一个具有固定大小UIImageView的自定义UITableViewCell子类。我已在我的博客here上详细说明了如何执行此操作。

我推荐1或3。

相关问题