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

ste*_*anB 6 cocoa-touch objective-c uitableview uikit ios

如何适应UITableViewCell(?)UIImage的单元格UITableView.

addSubviewcell或没有办法调整大小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;
Run Code Online (Sandbox Code Playgroud)

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

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

以上将图像添加到单元格,我可以计算尺寸以适应它,但是:

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

例:

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
Run Code Online (Sandbox Code Playgroud)

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

编辑: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];
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*lds 2

该网站发布了有关重新缩放UIImage*. 您可以使用缩放比例来获得适合UIImage*您正在使用的比例,然后将其缩小。