How to add UIScrollView to Interface builder?

Viewed 24644

I have all my controls laid out in interface builder (many labels, buttons etc). How do I put them all in a scroll view in interface builder so that I can have more space and be able to scroll up and down to reveal more controls? Do I have to do this programatically?

10 Answers

My preferred solution, where you don't need to hard-code the size of the contentSize:


NB: you might be able to avoid the source-code parts of this using the trick here: https://stackoverflow.com/a/11239123/153422 - although I haven't tried it yet.

The rest of this trick ... you still need to use anyway


  1. Move all controls into a single UIView (in IB: select all, then go Layout > Embed Objects In ... > View)

  2. Hookup that single UIView to your source code using an IBOutlet property (see below)

  3. IN SOURCE CODE, NOT INTERFACE BUILDER (IB is broken here, it has bugs where it sets the origin of the UIScrollView incorrectly - it tries to center the view. Apple never bothered to check it for basic bugs, sigh): Move the single UIView into a UIScrollView (see code below).

  4. Use sizeThatFits to "automatically" set the correct size.

Code (StackOverflow won't let me put code inside a numbered list. Sigh)

Header file:

/** outlet that you hook up to the view created in step 1 */
@property(nonatomic, retain) IBOutlet UIView *masterView;

Class file:

/** inside your viewDidLoad method */
[scrollview addSubview: masterView]; // step 3
scrollView.contentSize = [masterView sizeThatFits:CGSizeZero]; // step 4

...although I haven't checked this recently, IIRC it works on both 2.x and 3.x

Its easy:

First add a scrollview to your view. Change the size of the scrollview (e.g. make it 700 pixels long). Start putting your controls When you want to put/edit controls in the lower (invisble) part, select the scrollview and change the Y-start position to -300. Voila. After editing set the Y-start position back to 0 or whatever it was.

I know, this thread is a bit older... But somebody could find it on google, it's hight ranked. I wrote this little helper Method to get the job done:

- (void)addSubview:(UIView *)theSubView toScrollView:(UIScrollView *)theScrollView
{
    [theScrollView addSubview:theSubView];
    theScrollView.contentSize = theSubView.bounds.size;
}

You just have to declare two IBOutlet's in the header (e.g. contentView and scrollView) and call the method like this, whereever you want to load a UIView into a UIScrollView with your sourcecode:

[self addSubview:contentView toScrollView:scrollView];

I called it in viewDidLoad

This method features iOS

Related