Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you center a UIImageView in UITableViewCell regardless of orientation?

I'm trying to center a UIImageView width-wise in a UITableViewCell with the following code:

        // self.cover_image is a UIImage variable
        // cell is a UITableCellView

        UIImageView* backcover_imageview = [[[UIImageView alloc] initWithImage:self.cover_image] autorelease];
        [backcover_imageview sizeToFit];

        //center image
        //float xPos = cell.contentView.frame.size.width - (self.cover_image.size.width/2);

        //TODO: need better solution
        //Eyeballing attempt:
        float xPos = self.cover_image.size.width - 25;
        CGRect bookcover_frame = backcover_imageview.frame;
        bookcover_frame.origin.x = xPos;
        backcover_imageview.frame = bookcover_frame;
        backcover_imageview.tag = 9000;
        backcover_imageview.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;

        [cell.contentView addSubview:backcover_imageview];

I'm trying to center the UIImageView in a UITableCellView regardless of what orientation the iPad or iPhone device is in. Does anyone know the right way to do this?

like image 797
Alberto Leal Avatar asked Jun 17 '11 05:06

Alberto Leal


2 Answers

I added two more autoresizing masks and got a good result using your code and PengOne's answer:

playImage.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
[cell.contentView addSubview:playImage];
playImage.center = CGPointMake(cell.contentView.bounds.size.width/2,cell.contentView.bounds.size.height/2);
like image 107
Denis Kutlubaev Avatar answered Nov 15 '22 17:11

Denis Kutlubaev


After you add backcover_imageView to the contentView of the cell, use this to center it:

imageView.center = CGPointMake(cell.contentView.bounds.size.width/2,cell.contentView.bounds.size.height/2);
like image 45
PengOne Avatar answered Nov 15 '22 16:11

PengOne