8

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?

Alberto Leal
  • 520
  • 2
  • 10
  • 19

4 Answers4

13

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);
Denis Kutlubaev
  • 15,320
  • 6
  • 84
  • 70
7

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);
PengOne
  • 48,188
  • 17
  • 130
  • 149
  • 1
    I opted for `backcover_imageview.center = CGPointMake(cell.contentView.bounds.size.width/2,backcover_imageview.center.y);` which worked for me. Thanks for your suggestion! – Alberto Leal Jun 17 '11 at 18:13
  • 'CGPointMake' is unavailable in Swift. May be this is not working in current version of Swift. Solution is to use CGPoint as pointed out here : https://stackoverflow.com/a/39336801/783893 – Vineel Dec 23 '18 at 19:43
1

Can you try assigning the center property of cell to that of image view?

Something like this

imageView.center = cell.center;

And then add it to the cell.

0

You can use center anchors of the cell to keep the image in the center:

image.centerXAnchor.constraint(equalTo: cell.centerXAnchor).isActive = true
image.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true
Jan Polzer
  • 361
  • 2
  • 5