How to resize image to fit UITableView cell?

Posted by stefanB on Stack Overflow See other posts from Stack Overflow or by stefanB
Published on 2009-05-18T23:42:17Z Indexed on 2010/05/06 9:48 UTC
Read the original article Hit count: 562

How to fit UIImage into the cell of UITableView, UITableViewCell (?).

Do you addSubview to cell or is there a way to resize cell.image or the UIImage before it is assigned to cell.image ?

I want to keep the cell size default (whatever it is when you init with zero rectangle) and would like to add icon like pictures to each entry. Images are slightly bigger than the cell size (table row size).

I think the code looks like this (from top of my head):

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

What do I need to do to resize the image to fit the cell size? I've seen something like:

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

The above will add image to cell and I can calculate the size to fit it, however:

  1. I'm not sure if there is a better way, isn't it too much overhead to add UIImageView just to resize the cell.image ?
  2. Now my label (cell.text) needs to be moved as it is obscured by image, I've seen a solution where you just add the text as a label:

Example:

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

Could someone point me in correct direction?

EDIT: Doh [cell.contentview addSubview:view] not [cell addSubview:view] maybe I'm supposed to look at this:

- (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];
}

© Stack Overflow or respective owner

Related posts about iphone

Related posts about cocoa