dimme
dimme

Reputation: 4424

UIImageView inside a UITableViewCell

I'm trying to display a UIImageView inside a UITableViewCell.

Inside method - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath I have:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }


    CGSize cellSize = cell.frame.size;
    CGFloat cellWidth = cellSize.width;
    CGFloat cellHeight = cellSize.height;

    CGRect imageFrame = CGRectMake(0, 0, 70, cellHeight);
    UIImageView * image = [[UIImageView alloc] initWithFrame:imageFrame];
    [image setImage:[UIImage imageWithContentsOfFile:@"cyan.jpg"]];

    CGRect nameFrame = CGRectMake(80, 0, cellWidth-80, cellHeight/2);
    UILabel * nameLabel = [[UILabel alloc] initWithFrame:nameFrame];
    nameLabel.text = @"Name: John Doe";

    CGRect jobFrame = CGRectMake(80, 20, cellWidth-80, cellHeight/2);
    UILabel * jobLabel = [[UILabel alloc] initWithFrame:jobFrame];
    jobLabel.text = @"Job: IT-Consultant";

    [cell addSubview:image];
    [cell addSubview:nameLabel];
    [cell addSubview:jobLabel];

    return cell;
}

The labels are displaying perfectly but I don't see the image.

Any help would be appreciated.

Upvotes: 0

Views: 4209

Answers (3)

jrturton
jrturton

Reputation: 119242

imageWithContentsOfFile: expects a path to be sent to it. Use imageNamed: instead, or get hold of the path first by using NSBundle's pathForResource... methods first to get the path.

Also, if the image is the same for every cell, you should add the image view inside the cell=nil block, or you will be adding the view over and over again.

Upvotes: 6

Bourne
Bourne

Reputation: 10312

Use the UITableViewCell's imageView property instead of what you're doing. To be more clear, use cell.imageView.image and set your UIImage to that.

Or if you wish the image's location to be more flexible, add the imageView to the cell's contentView. i.e: [cell.contentView addSubview:yourImageView];

Upvotes: 1

gschandler
gschandler

Reputation: 3208

Add it to the UITableViewCell contentView instead.

[cell.contentView addSubview:...];

Upvotes: 2

Related Questions