如何调整图像大小以适应UITableView单元格?

时间:2009-05-18 23:42:17

标签: ios objective-c uitableview cocoa-touch uikit

如何使UIImage适合UITableView,UITableViewCell(?)的单元格。

您是addSubview还是cell还是可以在将cell.imageUIImage分配给cell.image之前调整其大小?

我想保持单元格大小默认(无论你使用零矩形初始化时是什么),并且想要为每个条目添加图片之类的图标。图像略大于单元格大小(表格行大小)。

我认为代码看起来像这样(从头到尾):

UIImage * image = [[UIImage alloc] imageWithName:@"bart.jpg"];
cell = ... dequeue cell in UITableView data source (UITableViewController ...)
cell.text = @"bart";
cell.image = image;

我需要做些什么来调整图像大小以适应单元格大小? 我见过类似的东西:

UIImageView * iview = [[UIImageView alloc] initWithImage:image];
iview.frame = CGRectMake(...); // or something similar
[cell.contentView addSubview:iview]

上面会将图像添加到单元格中,但我可以计算出适合它的大小:

  1. 我不确定是否有更好的 方式,是不是太开销了 添加UIImageView只是为了调整大小 cell.image
  2. 现在我的标签(cell.text)需要 移动,因为它被图像遮挡, 我见过你的解决方案 将文本添加为​​标签:
  3. 示例:

    UILabel * text = [[UILable alloc] init];
    text.text = @"bart";
    [cell.contentView addSubview:iview];
    [cell.contentView addSubview:label];
    // not sure if this will position the text next to the label
    // edited original example had [cell addSubview:label], maybe that's the problem
    

    有人能指出我正确的方向吗?

    编辑:Doh [cell.contentview addSubview:view]不是[cell addSubview:view]也许我应该看看这个:

    - (UITableViewCell *)tableView:(UITableView *)tableView
    cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell = ...;
        CGRect frame = cell.contentView.bounds;
        UILabel *myLabel = [[UILabel alloc] initWithFrame:frame];
        myLabel.text = ...;
        [cell.contentView addSubview:myLabel];
        [myLabel release];
    }
    

2 个答案:

答案 0 :(得分:2)

This site posts code重新调整UIImage*。您可以使用缩放来获得正在使用的UIImage*的正确比例,以缩小它。

答案 1 :(得分:1)

如果您可以访问apple devloper中心,则会有一个关于缩放图像视图的视频。它更侧重于性能问题并谈论很多线程,但他确实展示了一些用于调整图像大小的示例代码。

视频名称:“有效的iPhone应用程序开发 - 第2部分”约30分钟。