Andrew
Andrew

Reputation: 16051

UIImageView not rotating correctly?

I have a UIScrollView inside a UIViewController. It has scrolling and zooming enabled. It contains a UIImageView and when the user rotates the device, the idea is that the image stays centered. The problem is, when the device is rotated, it actually appears off to the left instead of center, where it should be staying. Here is the code I'm using. Set frame is called when the UIScrollView rotates:

-(void)setFrame:(CGRect)frame {

    float previousWidth = self.frame.size.width;
    float newWidth = frame.size.width;

    [super setFrame:frame];
    self.imageView.center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);

    [self setupScales];

    self.zoomScale = self.zoomScale * (newWidth / previousWidth);
}

Upvotes: 2

Views: 424

Answers (3)

Adam Kaump
Adam Kaump

Reputation: 735

I use the following layoutsubviews method in my subclass of uiscrollview:

- (void)layoutSubviews {
    [super layoutSubviews];

    if ([[self subviews] count] == 0) {
        return;
    }

    // center the image as it becomes smaller than the size of the screen
    CGSize boundsSize = self.bounds.size;
    CGRect frameToCenter = ((UIView*)[[self subviews] objectAtIndex:0]).frame;

    // center horizontally
    if (frameToCenter.size.width < boundsSize.width)
        frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
    else
        frameToCenter.origin.x = 0;

    // center vertically
    if (frameToCenter.size.height < boundsSize.height)
        frameToCenter.origin.y = ((boundsSize.height - frameToCenter.size.height) / 2);
    else
        frameToCenter.origin.y = 0;

    ((UIView*)[[self subviews] objectAtIndex:0]).frame = frameToCenter;
}

Upvotes: 1

mithlesh jha
mithlesh jha

Reputation: 343

If scrollview resizes with orientation change, try this

self.imageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;

Upvotes: 0

Simon Goldeen
Simon Goldeen

Reputation: 9080

You probably also need to set the contentOffset property of the scroll view

Upvotes: 0

Related Questions