Alex Rivera | Logout

How to add UIScrollView to Interface builder?

Asked 2009-10-05T17:19:12.937
21

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?

Edit
Report

1 Answer

25

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

answered 2009-12-12T14:49:00.060

Your Answer