Here’s two ways to embed/use a UIScrollView for your iOS application.

1. Embedded UIScrollView from storyboard.

Say you have a really large image

and you want the user to be able to scroll around your phone with it.

One way (if you are using storyboards) is to add a UIImageView to your ViewController. Select the UIImage and change it’s ViewMode from Scale to fit -> Top Left).

And then embed your image in a ScrollView by going Editor -> Embed In -> ScrollView.

If you Shift-Right-Click on your image you should see a ScrollView element there now.

Now the only left is to set the content size of our scroll view area to be the same size as our big image.

You can do this by dragging over the scrollView and imageView as properties and then setting the content size in viewDidLoad like this:

- (void)viewDidLoad
    [super viewDidLoad];
    self.scrollView.contentSize = self.imageView.image.size;

Now everything should scroll.

That’s probably the easiest way to setup a scrollable image.

2. Draw scrollview outside of ViewController and add after.

Now option#1 was good for scrolling images, but what if your scrollable design area is bigger than your Xcode ViewController area?

Now you don’t want the scrollable area nested in your view, because you won’t be able to see your design.

This option always you to keep your UIScrollView outside your view for design, and then add it after in the viewController like so:

- (void)viewDidLoad
    [super viewDidLoad];
    // set the content size to be the size our our whole frame
    self.scrollView.contentSize = self.scrollView.frame.size;
    // then set frame to be the size of the view's frame
    self.scrollView.frame = self.view.frame;
    // now add our scroll view to the main view
    [self.view addSubview:self.scrollView];

Big advantage of this option is it lets you see your design in Xcode in it’s entirety. Note this option was done with xibs – not storyboards (I havent figure out how to do this with storyboards yet).

But there you go. Two options for creating scrollviews.

A big thanks to Jeremy Gale (@jeremygale) for showing me option#2 with xibs (very handy).

Happy scrolling!

About these ads