【问题标题】:iOS: UIImageView changes with change in UITableView.rowHeight, how to avoid?iOS:UIImageView随着UITableView.rowHeight的变化而变化,如何避免?
【发布时间】:2014-08-31 00:08:35
【问题描述】:

这真的是一个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;

但随后图像也会按比例放大。

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

【问题讨论】:

    标签: ios objective-c uitableview uiimageview


    【解决方案1】:

    问题在于您使用的是默认的表格视图单元格样式。该样式带有内置的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 上有很多代码展示了许多其他方法。

    【讨论】:

    • 太棒了,正是我想要的,感谢您与我分享!
    【解决方案2】:

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

    你可以做的三件事:

    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 个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-15
      • 2021-12-05
      • 2014-06-25
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      • 1970-01-01
      • 2011-03-27
      相关资源
      最近更新 更多