louftansa
louftansa

Reputation: 515

Can't fit an image in a tableViewCell

I have a table view with grouped cells. I want one of this cell to contain an image. Here's my code to insert the image and make it fit in the cell :

             logoCell = [tableView dequeueReusableCellWithIdentifier:LogoCellIdentifier];
             if (logoCell == nil) {
                 logoCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:LogoCellIdentifier];
             }

             UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, logoCell.frame.size.width, 80)];
             [imgView setImage:image];

             [logoCell.contentView addSubview:imgView];

But my image is larger than the cell's width when the tableView is display. How can I make it fit the cell?

Upvotes: 1

Views: 931

Answers (3)

MJN
MJN

Reputation: 10808

How you add image views to UITableViewCells depends on what you're trying to do with the image view. If you want to have the image be a part of the cell's content, then add it upon cell creation.

logoCell = [tableView dequeueReusableCellWithIdentifier:LogoCellIdentifier];
if (logoCell == nil) {
    logoCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:LogoCellIdentifier];

    // ADD IMAGEVIEW ONLY WHEN CREATING CELL
    UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, logoCell.frame.size.width, 80)];
    [logoCell.contentView addSubview:imgView];

    // DONT ALLOW IMAGE OVERFLOW
    imgView.clipsToBounds = YES;
}

// SET YOUR IMAGE EVERY TIME
[imgView setImage:image];

If you're trying to set it as a background view, you should set the cell's backgroundView property in tableView:willDisplayCell:forRowAtIndexPath. Make sure that the image view is the same size as the cell.

UIImageView *imgView = [[UIImageView alloc] initWithFrame: cell.bounds];
imgView.image = image;
cell.backgroundView = imgView;

Upvotes: 1

rmaddy
rmaddy

Reputation: 318774

Create the UIImageView this way:

UIImageView *imgView = [[UIImageView alloc] initWithImage:image];
imgView.frame = CGRectMake(0, 0, logoCell.frame.size.width, 80);

Side note - make sure you are not adding a new UIImageView to the cell every time. You only want to add it once. Cells get reused as you scroll. Depending on how you implement your code, you can easily add multiple image views to the cell.

Upvotes: 0

Mark McCorkle
Mark McCorkle

Reputation: 9414

Add the image as a background color of the tableViewCell and you will get the nice rounded corners. Otherwise the grouped cell wont mask the image. You also need to set the contentMode of the UIImageView so it scales everything into the cell.

UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, logoCell.frame.size.width, 80)];
imgView.contentMode = UIViewContentModeScaleAspectFit;
cell.backgroundColor = [UIColor colorWithPatternImage:imgView.image];

Upvotes: 2

Related Questions