UIImage 作为 UITableViewCell 中的辅助视图未显示

Posted

技术标签:

【中文标题】UIImage 作为 UITableViewCell 中的辅助视图未显示【英文标题】:UIImage as accessory view in UITableViewCell not showing 【发布时间】:2013-07-22 17:35:44 【问题描述】:

在我的应用程序中,当提示用户选择一个项目时,我会打开一个 UITableView。根据商品是否有货、缺货、是否在订购等,我想在 UITableViewCell 的右侧显示一张图片。

我尝试使用附件视图按钮,但它没有显示在 UITableViewCell 上。我尝试将 UITableViewCellStyle 更改为 UITableViewCellStyleValue2(带有详细关闭按钮的样式),并且还尝试直接设置单元格的附件类型。

static NSString *CellIdentifier = @"MyCellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)

    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    //cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier];


[cell.textLabel setText:@"Testing"];
[cell.detailTextLabel setText:@""];

//cell.accessoryType = UITableViewCellAccessoryNone;
//cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;

UIImageView *imageView = [[UIImageView alloc] initWithImage:[myImageFilePath stretchableImageWithLeftCapWidth:0 topCapHeight:1.0]];
[imageView setContentMode: UIViewContentModeScaleAspectFit];
[imageView setFrame:CGRectMake(0, 5, cell.frame.size.height - 10, cell.frame.size.height - 5)];

cell.accessoryView = imageView;

return cell;

当应用运行时,UITableViewCells 会出现“Testing”文本,但单元格的右侧没有图像。

是否需要重写其他方法才能为详细信息披露按钮实现自定义 UIImage?

“按钮”更像是一个状态指示器,因为我不希望点击按钮执行与点击 UITableViewCell 上的其他任何位置不同的任何操作(只需选择行)。


一些附加信息:

如果我删除

[imageView setFrame:CGRectMake(0, 5, cell.frame.size.height - 10, cell.frame.size.height - 5)];

然后图片显示在 UITableViewCell 中,但是它太大了,放不下一行,所以它与其他行的辅助视图重叠。

我使用 setFrame 是为了调整图像的大小以适应 UIViewContentModeScaleAspectFit 以适应行,但它似乎完全阻止了图像的出现。

请注意,在此示例中 cell.frame.size.height = 44。


如果我将框架更改为:

[imageView setFrame:CGRectMake(0.0, 0.0, 120, 44)];

然后图像出现在行上。

但是,由于它是 120 像素宽,它会截断带有尾随 ... 的文本。图片可以在尾随 ... 之前放置大约 3 倍,宽度为 120,高度为 44。

如何让尾随 ... 更接近图像?

如果我将 120 降低到一个较低的值,图像会向右移动并最终跑出单元格。

【问题讨论】:

【参考方案1】:

UITableView 的宽度是 804。将其更新为 768 允许我使用发布的原始代码。

【讨论】:

【参考方案2】:

您的问题与此处的问题非常相似: Using a custom image for a UITableViewCell's accessoryView and having it respond to UITableViewDelegate

除非需要,否则您可以忽略“让它响应”位。但是,正如您在此处看到的,对于 accessoryView 属性,矩形是正方形的,因此 120x44 的图像可能永远无法正确拟合。

我会重新考虑您解决此问题的方法,并创建一个自定义 UITableViewCell 子类,其中包含您需要的必要项目(听起来像 UILabel 和 UIImageView)。这样,您可以轻松控制标签的大小与图像的大小、标签如何换行(如果完全换行或可能被截断)等等。

【讨论】:

【参考方案3】:

另一种方法是子类化 UITableviewCell 并在“layoutSubviews”中设置框架,并确保为每个单元格传递正确的行高。

通过子类化,您将获得完全的灵活性。

希望对你有帮助

【讨论】:

【参考方案4】:

我猜你的 CGRect X 和 Y 有问题,在这种情况下是 0 和 5。也许尝试动态设置它们可以解决这个问题。告诉我

【讨论】:

我尝试将 X 设置为 cell.frame.size.width-44,但仍然不可见。

以上是关于UIImage 作为 UITableViewCell 中的辅助视图未显示的主要内容,如果未能解决你的问题,请参考以下文章

将 UIImage 视图作为子视图添加到 UIView 的实例

我可以将 UIImage 作为文本放在 textview 中,以便我可以在 ios 中将它们作为文本删除

动态处理多维数组作为 UIImage 数组

将 UIImage 作为二进制数据保存到 CoreData 实体时出错

UIImage 作为 UITableViewCell 中的辅助视图未显示

Re: 快速从 UIImage/CGImage 获取像素数据作为数组