TigerCoding
TigerCoding

Reputation: 8720

Centering UIImageView in UItableViewCell doesn't work, how to fix?

I can subclass the cell and resolve the problem, but I'd like to know why this doesn't work.

I set an image in the cell, then in this method, I move the image to the right:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
        [cell.imageView setFrame:CGRectMake(cell.contentView.bounds.size.width/2 - cell.imageView.frame.size.width/2 + 100,
                                            cell.contentView.bounds.size.height/2 - cell.imageView.frame.size.height/2,
                                            cell.imageView.frame.size.width,
                                            cell.imageView.frame.size.height)];
        NSLog(@"center: %@", NSStringFromCGPoint(cell.imageView.center));
        NSLog(@"frame: %@", NSStringFromCGRect(cell.imageView.frame));
}

Notice the +100 I added to ensure it's over to the right.

When I check the console, it indicates this:

center: {250, 57.5}

frame: {{150, 7.5}, {200, 100}}

However the output is this:

grouped cell image

The image is still aligned to the left side. Can this be changed, and if so, how?

Upvotes: 2

Views: 749

Answers (2)

Alex Terente
Alex Terente

Reputation: 12036

You can not move the image view. Solution is or to subclass and do your own drawing in drawRect, or to add a subview to the cell.contentView.

Edit:

If an image is set, it appears on the left side of the cell, before any label. UITableViewCell creates the image-view object when you create the cell.

From UITableViewCell Class Reference

Upvotes: 1

Ankit Srivastava
Ankit Srivastava

Reputation: 12405

if you go to the header file of UITableViewCell than there you will find...

> // Content.  These properties provide direct access to the internal
> label and image views used by the table view cell.  These should be
> used instead of the content properties below.
> @property(nonatomic,readonly,retain) UIImageView  *imageView
> __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);   // default is nil.  image view will be created if necessary.

so as you can see it says readOnly property to the image view... I think this explains your inability to move the imageView.

Upvotes: 3

Related Questions