如何在 Interface Builder 中使用 UIScrollView?

虽然我过去曾经通过编程的方式成功地使用过 UIScrollView,但是如果只在 Interface Builder 中设置它,我就很难让它正常工作。

我的 iPhone 应用程序中有一个简单的“关于”页面。它有一个 UITextView,一些图标,并链接到我的其他应用程序。我已经把所有这些视图添加到我的 UIScrollView,安排它们,使它们的总大小 > 480。当我启动应用程序时,scrollview 只显示屏幕上适合的内容,没有滚动条。

是否可以完全通过 IB 来完成,或者必须通过代码来操作 contentSize?

65603 次浏览

You forgot to set the contentSize property of the UIScrollView. Strangely enough you can not do this from Interface Builder. You will have to do it from the view controller managing this scroll view.

Now there is a way to make a UIScrollView scroll without leaving Storyboard:

  1. Select the UIScrollView in the Storyboard, go to the Size inspector and change the Bottom value (or whatever other value you need to change) in the Content Insets section to the height of the content area.
  2. Now go to the Identity inspector and create a new User Defined Runtime Attribute (by clicking the + button) and name it contentSize. It doesn't matter what Type or Value you fill in (you can even leave their default value).

This will make the UIScrollView work properly, although I don't know why the second step is necessary (I found out by chance). :(

Boby_Wan's answer got me thinking, and I found the following solution to configure the UIScrollView's contentSize from Interface Builder:

  1. Select the UIScrollView in the Storyboard scene
  2. Go to the Identity inspector, create a new User Defined Runtime Attribute (click the + button)
  3. Change the attribute Key Path to contentSize
  4. Change the attribute Type to Size
  5. Now set the Value to {desired content width, desired content height}

eg setting the value to {320, 920} will let the user scroll down a whole extra screen on the iPhone.

(I am using xcode 4.3.3, the project's iOS Deployment Target is 5.1)

When I first did this I received the following error:

Illegal Configuration:
     Size type user defined runtime attributes with Xcode versions prior to 4.3
     MainStoryboard.storyboard

If you too get this error it is simple to fix: select the Storyboard in the Project Navigator, and bring up the File inspector. Find/expand the Interface Builder Document section, and there is a drop down for Development. Ensure this is set to Xcode 4.3

one approach i have used in the past is to drag the scrollview out of it's containing view in interface builder, and set it's actual size to what want the contentSize to be.

what is not inherently obvious about interface builder is you can have unassociated views that are stored in the nib, but aren't a part of the main view the nib is primarily for.

in the view where you want it the scrollview to live, place a simple UIView, which you use as a place holder. (this is simply so you can visually design it's location. if you are just using the entire view, you can skip this step and use the second code snippet i supply at the end of this answer).

you can then populate the scrollview with controls, visually laying it out how you want it to be. give both the placeholder and the scrollview properties inside your view controller so you an access them at runtime.

at runtime, in - (void)viewDidLoad

scrollView.contentSize = scrollView.frame.size;
scrollView.frame = placeholder.frame;
[placeholder.superview addSubView:scrollView];
[placeholder removeFromSuperview];

alternatively (if you didn't use a placeholder):

CGRect f = self.view.frame;
scrollView.contentSize = f.size;
f.origin.x = 0;
f.origin.y = 0;
scrollView.frame = f;
[self.view addSubView:scrollView];

finally, if you "lose" your scroll view in interface builder (it's possible to close it so it disappears from the design grid), don't panic. just click on it in the object list to the left of the design grid.

You can do it using only Interface Builder, go to the Identity Inspector (the third inspector tab) and add a new User Defined Runtime attribute with

  • Key Path: contentSize
  • Type: Size
  • Value: {width, height}

In Xcode 4.5 using Autolayout I have no Content Insets section in my size inspector. So I had to add it under User Defined Runtime Attributes and then it worked fine.

What you add in "User Defined Runtime Attributes" is keyPath == contentInset which is of type "Rect" (UIEdgeInsets, which has the same input as a Rect) and is defined as {top, left},{bottom, right}. The contentSize only defines the region of the scrollview window. contentInset defines the scrollable area.

I hope this helps somebody in the same situation.

With Autolayout (iOS6+), you can avoid setting contentSize. Set the following constraints instead:

  1. Pin the top of the scrollview to the top of its top-most child.
  2. And pin the bottom to the bottom of its bottom-most child.

If you click on the Properties icon of any View Controller in Interface Builder, you can set it to a "Freeform" size in Simulated Metrics and change the size of the main View to be your desired content size.

This way you can create your ScrollView's content as if it were one large view. As it's only a simulated metric your View Controller will be resized to the window's bounds when it's loaded.

Setting up a UIScrollView via Interface Builder is not intuitive. Here is my checklist for setting it up:

  1. Select the UIViewController's XIB file. In the interface builder's "Identity Inspector", change the UIView to class type UIScrollView

  2. Under "File Inspector", uncheck Autolayout

  3. Under "Attributes Inspector", change the size to Freeform. You can then stretch the Scroll View manually or you can specify a custom width and height under "Size Inspector".

  4. In "Identity Inspector", add a new User Defined Runtime Attribute called "contentSize" of type "Size" and change it to a value like {320, 1000}. You cannot set this programmatically anymore and therefore need this step so that Scroll View knows that contents of the Scroll View are bigger than the window.

Here's a solution to design ScrollView with a content larger than the screen entirely in Storyboard (well, almost entirely, you'll need to add 1 single line of code too)

https://stackoverflow.com/a/19476991/1869369

I find out a more convenient way.

1: Scale the size of the scroll view to contain all the ui inside it.

2: Add a iboutlet of the scroll view.

3: In viewDidLoad, save the frame.size of the scroll view.
(e.g. _scrollSize = _scrollView.frame.size;)

4: In viewWillAppear, set the contentSize by the CGSize you saved before.
(e.g. _scrollView.contentSize = _scrollSize;)

5: Done~

Just remove the autoLayout on your scrollview. then the code is as simple as this:

scrollviewName.contentSize = CGSizeMake(0, 650);

just create an iboulet property on .h file then synthesize on .m file. Make sure that the scrolling is enabled.

Yes, st3fan is right, UIScrollView's contentSize property must be set. But you should not turn off autolayout for this purpose. You easily can setup contentSize of UIScrollView with autolayout in IB only, without any code.

It is important to understand that when using autolayout contentSize of UIScrollView is not set directly, it is calculated based on constraints of all subviews of UIScrollView. And all you need is to provide proper constraints for subviews for both directions.

E.g. if you have only one subview you can set its height and space from top and bottom to superview (i.e. scrollView in our case) contentSize.height is calculated as sum

Vertical Space (aSubview.top to Superview.top) + aSubview.height + Vertical Space (aSubview.top to Superview.top)

contentSize.width is calculated similarly from horizontal constraints.

If there too few constraints to calculate contentSize properly small red button is shown near View Controller Scene item to inform about layout ambiguity.

If there are many subviews then it may be "chain" of constraints: top to topmost subview, heights and spaces between subviews and bottommost subview to bottom like in Danyal Aytekin answer.

But in practice in most cases it is more convenient just to add a empty view with required size and set spaces to top, left, bottom, right of scrollView to 0. You can use this view as "content View" i.e. put all other subviews on it or if you already have many subviews and do not want move them and setup layout again you can add this auxiliary view to existing subviews and made it hidden.

To make scrollView scrollable calculated contentSize must be greater than scrollView size.

You can have UIScrollView in StoryBoard with Autolayouts. Basically what do you need is:

  1. Add UIScrollView
  2. Add all constraints to it (like insets from top, left, right, bottom edges)
  3. Add a 'container' UIView to UIScrollView
  4. If you want just one-direction scroll (say, vertical): set height explicitly (for the instance, 600) and link width to the width of UIScrollView.
  5. If you want two-directional scroll just set both width and height.

storyboard setup

  1. Add UIViewController
  2. In UIViewController 'Attribute Inspector -> Simulated Metrics' set size Freeform
  3. In UIViewController 'Size Inspector -> View Controller' set height 800
  4. Add UIScrollView in UIViewController
  5. Add all constraints to UIScrollView (top, left, right, bottom) and add alignment X = center
  6. Add UIView in UIScrollView
  7. Add all constraints to UIView (top, left, right, bottom) and add alignment X = center. Yes, same as for UIScrollView in #3, but for UIView
  8. Add height constraint to UIView. For example 780
  9. Run

Storyboard

Many of the answers above are misleading or outdated. As of 2017 (possibly much earlier) interface builder does support scrollviews with automatically sized content. The trick is that XCode gives a special, non-standard meaning to the constraints between the scrollview and the content inside it. These "inward" constraints will not actually affect the size of the content as you might otherwise expect.

This means that you can e.g. have your scrollview pinned to the bottom of the main view with zero margin, and also have your scrollview's content pinned to the bottom of the scrollview with zero margin, but the content will not actually be stretched by this. Instead the content will get its self-determined size (more below) and this will also be the size of the scrollable area within the scrollview.

Think of it like this - There is an asymmetry in binding constraints to a scrollview: Constraints from the scrollview to the "outside" (parent) world determine the size and position of the scrollview as usual. But constraints "inside" the scrollview are really setting the size and position of the scrollable area of the scrollview, by binding it to the content.

This is totally non-obvious because when you go to set the constraints XCode will always suggest the current spacing and it might never occur to you to intentionally change the inward and outward facing constraints in a way that conflicts. But you can and they have the meaning described above: one controls the scrollview layout and one controls the scrollable content area size.

I stumbled upon this by accident and then seeing how it appeared to work lead me to this article that explains it completely and cites the Apple docs source for this:

https://spin.atomicobject.com/2014/03/05/uiscrollview-autolayout-ios/

One last critical piece of information, about the content's self-determined size: You may feel that you are in a catch-22 here because you normally size your content to e.g. the parent view's width, but in this case the parent is the scrollview and as described above - the constraint will not affect your content size. The answer here is to remember that you can constrain items to items not directly neighboring in your view hierarchy: e.g. You can set the width of your content view to the width of the main view instead of trying in vain to get the scrollview to do it for you.

Create a new Xcode Project

Navigate to Main.storyboard file

Select ScrollView from the objects library.

Set frame for the ScrollView.

Add another view to scroll view and keep the frame same as that of ScrollView.

Now to set its height and width dynamically you may this Configure A UIScrollView Using Auto Layout In XIB

You can do it entirely in Interface Builder without setting the "contentSize" property in code.

  1. Put only one View in Scroll View. The Scroll View should only has this child view. You can name it as Content View. And put all contents inside this View later.
  2. Align four edges of this View to the Scroll View (the View's superview) with zeros.
  3. Set the width and height of this View. The width and the height will be implicitly treated as the "contentSize" of the Scroll View.

Simply put, the width and height of this View define the "contentSize" of the Scroll View. Because this View is the only content of the Scroll View, the size of this View is the content size of the Scroll View. It is quite reasonable.

I learned it from this tutorial: https://riptutorial.com/ios/example/12812/scrolling-content-with-auto-layout-enabled