I have been unable to find the answer for this issue I am having.
I have a UIImageView inside a UIScrollView, and I would like the center its content vertically.
Right now, the only way I have been able to do this is by setting the scroll view's contentInset based on the height of the UIImageView size, but this is not a perfect solution; it just increases the size of the UIImageView, making the UIScrollView 'think' its content is bigger, and adds these black bars to the top.
I've tried to get help from:
UIScrollView with centered UIImageView, like Photos app
and
Center content of UIScrollView when smaller
But have not been able to solve it using those answers.
This code should work on most versions of iOS (and has been tested to work on 3.1 upwards, which is all I currently have access to).
It's based on the Apple WWDC code mentioned in Jonah's answer.
Add the below to your subclass of UIScrollView, and replace tileContainerView with the view containing your image or tiles:
- (void)layoutSubviews {
[super layoutSubviews];
// center the image as it becomes smaller than the size of the screen
CGSize boundsSize = self.bounds.size;
CGRect frameToCenter = tileContainerView.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;
tileContainerView.frame = frameToCenter;
}
You can tell the UIScrollView to scroll to specific view by calling scrollRectToVisible:animated:
Example:
[myScrollView scrollRectToVisible:imageView.frame animated:YES];
To center it vertically, try this:
1) Add an empty view to your scrollview that is the same height of your contentSize.
2) Add your UIImageView to the center of the emptyView
2) scrollRectToVisible
on this empty view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With