如何调整自定义tableview单元格下的UIImageview

Posted

技术标签:

【中文标题】如何调整自定义tableview单元格下的UIImageview【英文标题】:How to adjust the UIImageview under custom tableview cell 【发布时间】:2016-03-28 08:24:28 【问题描述】:

我有一个自定义表格视图,并且在每个单元格下我都有图像视图。我从服务接收不同尺寸的图像,我想据此调整我的框架。

每当有图片小于框架尺寸时,我想根据它的高度调整高度。

所以我正在比较当前帧大小和图像大小并尝试更新 imageview 帧,但它不起作用。

cell.image.contentMode = UIViewContentModeScaleAspectFit;
        if(cell.image.image.size.height<cell.image.frame.size.height)
        
        cell.image.frame = CGRectMake(cell.image.frame.origin.x, cell.image.frame.origin.y,cell.image.frame.size.width, cell.image.image.size.height);
        

需要做些什么来克服这个问题??

【问题讨论】:

【参考方案1】:

您需要像这样根据 UITableView 数据源中的图像更改单元格高度

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

  if (image.size.width > CGRectGetWidth(self.view.bounds)) 
    CGFloat ratio = image.size.height / image.size.width;
    return CGRectGetWidth(self.view.bounds) * ratio;
   else 
    return image.size.height;
  

编辑 如果您正在寻找调整图像大小而不是 tableview 单元格,那么这些是 Resize UIImage with aspect ratio? 和 Resize UIImage with aspect ratio? 非常好的参考。你也应该明白UIImageView Scaling Explained Visually

【讨论】:

所以我不需要在 cellForRowAtIndexPath 下做任何事情?? @aman.sood 是的,只需将图像设置为您的 UIImageView。还要检查自定义单元格 xib 什么是视图 -> 模式设置,它应该是缩放填充 但是在 heightForRowAtIndexPath 中声明单元格对象给了我异常 我尝试添加 TimelineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];在 heightForRowAtIndexPath 下 对不起我的错。它不应该是单元格,因为单元格仍然不在内存中,我只是复制了你的代码。因此,您应该在 heightForRowAtIndexPath 中提供图像对象【参考方案2】:

如果上面的代码在 cellForRowAtIndexPath 中,并且您在 cellForRowAtIndexPath 中初始化的单元格是 ItemCell 的一个实例(例如),那么在您的 ItemCell 类中,您将必须覆盖 layoutSubviews 并检查内部图像子视图的大小layoutSubviews 并在 layoutSubviews 中相应地调整单元格框架的高度。这确保了每次调用 cellForRowAtIndexPath 时,UITableViewCell 子类 (ItemCell) 的布局发生在 cellForRowAtIndexPath 渲染单元格之前。

顺便说一句,您已将单元格的 contentMode 设置为 ScaleAspectFit 的事实意味着,无论您对单元格内的 imageView 的框架做什么,图像都将始终缩放以适合它可用的整个视图,即在这种情况下,单元格内的 imageView 的尺寸。也许您应该尝试移动 contentMode 行

 cell.image.contentMode = UIViewContentModeScaleAspectFit;

在您设置 imageView 的帧大小的条件之后:

    if(cell.image.image.size.height<cell.image.frame.size.height)
    
    cell.image.frame = CGRectMake(cell.image.frame.origin.x, cell.image.frame.origin.y,cell.image.frame.size.width, cell.image.image.size.height);
    
cell.image.contentMode = UIViewContentModeScaleAspectFit;

当然,如果您不覆盖 layoutSubview 来调整 imageView 框架的尺寸,这可能无法解决问题。

【讨论】:

是的,它在 cellForRowAtlndexPath 内部,你能告诉我如何覆盖那个 layoutSubviews 吗? @达斯

以上是关于如何调整自定义tableview单元格下的UIImageview的主要内容,如果未能解决你的问题,请参考以下文章

强制页脚停留在表格视图中的最后一个单元格下

如何调整自定义 UITableViewCell nib 文件的大小以适合 tableView?

如何在自定义 tableView Cell 中调整标签高度和宽度

Tableview推送到不同的视图

如何在使用 tableViews 自调整单元格时在运行时更改表格视图单元格高度?

隐藏静态表视图控制器中最后一个单元格下的空白行[重复]