How can I use Autolayout to set constraints on my UIScrollview?
Asked Answered
N

18

177

I have spent two days trying out the various solutions for Mixed and Pure Autolayout approaches to achieve what was a trivial scrollview setup prior to autolayout, and it's now official - I must be too stupid. I am setting this up mostly in Storyboard (well, it's just the way it is).

So here's my plea for help.

Viewtree:

UIView
-UIView
-UIView
..-UIScrollview
...-UIButton
...-UIButton
...-UIButton

The buttons are supposed to scroll horizontally (left to right and vice versa). Can someone please let me know how to set the constraints to achieve this using pure Autolayout???

--

I have tried the mixed approach, like so:

UIView
- UIView
- UIView
..-UIScrollview
...-UIView (contentview)
....-UIButton
....-UIButton
....-UIButton

...and setting fixed width and height constraints for the contentview and the translatesAutoresizingMaskIntoConstraints settings as per Apple's TechNote. The buttons and scrollview are set up using constraints. This gets the scrollview scrolling (yay) but alas, it scrolls too far! As far as I can tell, the scroll width is somehow doubled from what I set the contentview at???!!!???

I tried the pure autolayout approach as well, both with contentview and without. All the views are translatesAutoresizingMaskIntoConstraints=NO, except for self.view. The buttons have fixed width/height constraints, and are pinned to all four edges of the scrollview. Nothing scrolls.

So I am totally baffled why I can't get it to work correctly. Any help is much appreciated, and if you need any other info, please ask!

UPDATED Screenshot with solution - buttonZ constraints:

enter image description here

EDIT @ Jamie Forrest So the solution turns out to be the wrong trailing constraint on the last button. Instead of 6441, the value I had set was negative, -6441. The tricky thing is, that when setting the value in storyboard, there are two options in the Pin toolbar:

enter image description here

The Current Canvas Value is negative (leading to no scroll), and the option below is positive (activating scroll). This means I'm not stupid but at least half-blind I guess. Although, to my defense, isn't it somewhat disturbing that XCode doesn't show an error for the "incorrect" setting?

EDITED AGAIN Now this is funny... changing the trailing value from -6441 (no scroll) to 6441 enabled scroll. But my old friend the "too much contentsize" was back, leading to a content size twice as large as what it should be! The solution to get the correct content scroll was to set the trailing constraint to ZERO! This is not obvious when working in Storyboard but looking at @Infinity James' code, it is what it should be.

Nighttime answered 26/11, 2013 at 16:47 Comment(14)
Where do you calculate/set the content size for your scroll view? Referring to your first attempt using a contentView and you said it scrolls too far.Cele
As far as I know, you can't set the contentSize of an UIScrollView using only auto layout. And it's the contentSize that defines how much you can scroll. So you'll have to set this manually somewhere eventually. For the rest, you can use layout constraints to set up view frames relative to each other.Frivol
@Jeff, the content size is fixed, it never changes. I set the content size in the storyboard by entering the correct height and width for the contentiview manually, and I pin the height and width with constraints in the storyboard.Nighttime
Print out your contentSize at run time, see if it matches the values you have input. The contentSize determines how much scroll occurs, so the issue with your first attempt is to do with contentSize.Cele
@Guillaume, so the "pure autolayout" approach isn't that pure after all? But HOW do I set the contentSize manually? As I mentioned above, I am setting the height/width of the content view at fixed values (in the storyboard). But it scrolls too far (2x).Nighttime
@Jeff, I understand that. Obviously, if the contentsize was correct, it would scroll correctly. The problem as I am trying to describe is: how to set the contentsize correctly? Apple's TechNote seems to sidestep the issue by using an imageview, or so it feels. I will log the contentsize and respond here shortly.Nighttime
@Nighttime To set it manually just do this: scrollView.contentSize = CGSizeMake(THE_SIZE_OF_THE_CONTENT,self.scrollView.frame.size.height);Hoshi
@Jeff, the contentsize is logged as twice the one I set the contentview.width at. Since it scrolls twice as far, that's obvious I guess. The question is - why does it scroll twice as far if I set the width of the contentview to half of it?Nighttime
@Blue Gene, this won't work with pure autolayout but yes, this is what I used for the mixed approach.Nighttime
@Nighttime yes but you asked how to set it manually.Hoshi
Video tutorial: youtube.com/watch?v=4oCWxHLBQ-APharmacist
Perfect solution! --> "The solution to get the correct content scroll was to set the trailing constraint to ZERO! This is not obvious when working in Storyboard"Vesture
I prefer the old question title.Firmin
@Frivol "You don’t have to set the content size of the scroll view" when using a pure Autolayout", approach. See Apple TN2154: "UIScrollView And Autolayout"Emblem
C
70

It's hard to see the exact values and setup of your constraints as you've pasted them here, so I'm not sure from looking at your screenshots where you have gone wrong.

In lieu of an explanation of what's wrong in your setup, I've created a basic sample project with a very similar view hierarchy and constraint setup to the one you describe. The horizontal scrolling works as expected in the sample project, which uses the "Pure AutoLayout" approach that Apple describes in the Technical Note.

I also had a lot of trouble originally getting Auto Layout to work with UIScrollView. The key to getting it to work is making sure that all of the items in the scroll view, taken together, have constraints that eventually link to all sides of the scroll view and that contribute to the AutoLayout system being able to determine a contentSize for the scroll view that will be bigger than its frame. It looks like you were trying to do that in your code, but maybe you had some superfluous constraints in there that were making the contentSize too small.

Also of note, as others mentioned, with AutoLayout and UIScrollview, you no longer set the contentSize explicitly. The AutoLayout System calculates the contentSize based on your constraints.

I also found this ebook chapter to be very helpful in making me understand how all this works. Hope all this helps.

Clericalism answered 27/11, 2013 at 2:41 Comment(11)
THANK YOU for the sample project! It works, and while looking through it, I couldn't find any difference to my project at first! I copied the views into my project, suspecting some other setting than constraints, but it continued to work. This led me to notice that the trailing constraint for the last button in my project has a negative - in front of it, while yours has a positive value! Changing the - to positive enabled the scroll! When I bring up the Pin toolbar, there are two choices: Use Current Canvas value, which is negative, and Scroll View (use current value) which is positive...?!Nighttime
Ah, yes. The negative value would actually make the contentSize of the scroll view smaller, to match the fact that the trailing edge should end before the button ends. Glad the sample project helped!Clericalism
It did a lot. Check out my updated answer. The trailing value should actually be 0 (zero) it seems.Nighttime
Glad you figured it out. One thing to keep in mind is that you can still use the scroll view's contentInset to control "padding" around the scrollview. That would've been the wrong approach to fix your 6441 points of padding in your case, but in general it's good to know that contentInset still works as expected.Clericalism
That is sad thing we have to share screenshots instead of code. That is just because apple encourages developers to use builder instead of providing better api.Brightman
A small trip hazard I came across is that if the width/bounds of the scroll view aren't well defined then the bounds of the scroll view can change size to make room for its content instead of the content size changing.Suspensor
The sample project does the job. Very easy explanation. Thanks a lot!Zestful
Totally unintuitive. Developers have to squander hours and hours to figure what was going on on XCode´s creators´ mind.Willumsen
This project is really inspiring :)Workroom
@JamieForrest can u help me ? #33646738Maiolica
Thanks bro, your repository solved my issue and explained the mechanism.Lacrimatory
I
50

LOL welcome to the stupidity club. I'm one of the founders. :D

For VERTICAL scrolling: the only way I could get it to work (iOS 8, Xcode 6 and pure autolayout) was adding the following constraints to my Scroll View (all related to the superview):

  • Equal Widths
  • Equal Heights
  • Center Y Alignment
  • Center X Alignment

My structure:

  UIView
   - ScrollView
    - Subview
    - Subview
    - Subview
    - Subview
    - ...

This is the final result:

Demo

This is the setup:

Setup Full screen

And here is the project.

Hopefully this would save someone from GOING TO SLEEP AT 5 AM. :D

Ignoble answered 27/12, 2014 at 22:13 Comment(9)
Thanks a lot for the help! How did you get the subview of type "subview" ?? I'm looking at your project in Xcode 6.2, and it calls those little rectanges "Subview" with the only constraint being that it's 63px high.Latrell
Greetings! That "Subview" is actually an UIVIew. That is just a name... You can type anything there. Check out this image: cl.ly/image/291f1K2N0V3p On the constraint topic, the subviews have more than just a height constraint. Check the entire constraint list for those views here: cl.ly/image/3l061i123j2iIgnoble
I'm still not able to get scrolling working -- I noticed that your subviews views are "greyed out" in your project. After doing some research, it looks like this is because you are using 'size classes.' How does this affect the scrolling? Is there a way to get the scrolling working without using this?Latrell
Also, how did you make your superview so much longer than the default length? I'm trying to add buttons that will appear "below the fold" (or off screen) but obviously I cant add them to the superview if I cannot drag and drop them onto the superview since it's not big enough.Latrell
Yes, I'm using size classes. Set "Compact-Regular" in the Storyboard and you will be fine. Refer to this: cl.ly/image/3O3C1D2n1i3p And you can set whatever height you want in your Scroll View. I set mine to 900. Refer to this: cl.ly/image/3L0G2O0a3i33Ignoble
after a long day of searching and trying to do this stupidity layout, I found this answer and works at the first try.. Thanks man.. you save my day.. I wish I could give thousand up vote for this answer.. :)Wesle
Life saver. Thanks for the answer mate. Adding centre X and Y to relate Content View to Scroll View did the trick.Naumann
Awesome, saved me. Thanks alot!!Tierza
I joined the club as well. Thanks man for solution (not an easy one though) :DNoodle
B
32

Simple Self-Contained Example

Judging by the high number of votes on the question and the low number of votes on the answers, people are not finding an understandable and quick solution here. Let me try to add one. This project is a self-contained example done completely in the Interface Builder. You should be able to work through it in 10 minutes or less. Then you can apply the concepts you learned to your own project.

enter image description here

The original question asks about scrolling buttons. Here I just use UIViews but they can represent whatever view you like. I also chose horizontal scrolling because the storyboard screenshots are more compact for this format. The principles are the same for vertical scrolling, though.

Key concepts

  • The UIScrollView should only use one subview. This is a 'UIView' that serves as content view to hold everything you wish to scroll.
  • Make the content view and the scroll view's parent have equal heights for horizontal scrolling. (Equal widths for vertical scrolling)
  • Make sure that all of the scrollable content has a set width and is pinned on all sides.

Start a new project

It can be just a single view application.

Storyboard

In this example we will make a horizontal scroll view. Select the View Controller and then choose Freeform in the Size Inspector. Make the width 1,000 and the height 300. This just gives us room on the storyboard to add content that will scroll.

enter image description here

Add a Scroll View

Add a UIScrollView and pin all four sides to the root view of the view controller.

enter image description here

Add a Content View

Add a UIView as a subview to the scroll view. This is key. Don't try to add lots of subviews to the scroll view. Just add a single UIView. This will be your content view for the other views you want to scroll. Pin the content view to the scroll view on all four sides.

enter image description here

Equal Heights

Now in the Document Outline, Command click both the content view and the scroll view's parent view in order to select them both. Then set the heights to be equal (Control drag from the Content View to the Scroll View). This is also key. Because we are scrolling horizontally, the scroll view's content view won't know how high it should be unless we set it in this way.

enter image description here

Note:

  • If we were making the content scroll vertically, then we would set the content view's width to be equal to the scroll view's parent's width.

Add content

Add three UIViews and give them all constraints. I used 8 point margins for everything.

enter image description here

Constraints:

  • Green view: pin the top, left, and bottom edges. Make the width 400.
  • Red view: pin the top, left, and bottom edges. Make the width 300.
  • Purple view: pin all four edges edges. Make the width whatever the remaining space is (268 in this case).

Setting the width constraints is also key so that the scroll view knows how wide its content view will be.

Finished

That's all. You can run your project now. It should behave like the scrolling image at the top of this answer.

For vertical scrolling, just swap all the width and height directions in this example (tested and working).

Further Study

Buckman answered 18/6, 2016 at 4:46 Comment(0)
S
9

The contentSize is implicitly set by applying the constraints inside of the UIScrollView.

For example, is you have a UIScrollView inside of a UIView it will look like this (as I am sure you are aware):

    UIView *containerView               = [[UIView alloc] init];
    UIScrollView *scrollView            = [[UIScrollView alloc] init];
    [containerView addSubview:scrollView];
    containerView.translatesAutoresizingMaskIntoConstraints = NO;
    scrollView.translatesAutoresizingMaskIntoConstraints    = NO;
    NSDictionary *viewsDictionary       = NSDictionaryOfVariableBindings(containerView, scrollView);

    [containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[scrollView]|"
                                                                          options:kNilOptions
                                                                          metrics:nil
                                                                            views:viewsDictionary]];
    [containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[scrollView]|"
                                                                          options:kNilOptions
                                                                          metrics:nil

That will set the scrollView to fill the size of the containerView (so the containerView will have to be of a certain size).

You can then adjust the contentSize of the UIScrollView by implicitly setting it to be large enough to hold the buttons like this:

    UIButton *buttonA                   = [[UIButton alloc] init];
    UIButton *buttonB                   = [[UIButton alloc] init];
    UIButton *buttonC                   = [[UIButton alloc] init];
    [scrollView addSubview:buttonA];
    [scrollView addSubview:buttonB];
    [scrollView addSubview:buttonC];
    buttonA.translatesAutoresizingMaskIntoConstraints       = NO;
    buttonB.translatesAutoresizingMaskIntoConstraints       = NO;
    buttonC.translatesAutoresizingMaskIntoConstraints       = NO;

    viewsDictionary                     = NSDictionaryOfVariableBindings(scrollView, buttonA, buttonB, buttonC);

    [scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[buttonA]-|"
                                                                       options:kNilOptions
                                                                       metrics:nil
                                                                         views:viewsDictionary]];
    [scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[buttonA]-[buttonB]-[buttonC]-|"
                                                                       options:NSLayoutFormatAlignAllBaseline
                                                                       metrics:nil
                                                                         views:viewsDictionary]];
Sanderlin answered 26/11, 2013 at 17:58 Comment(4)
So, I set the constraints between the scrollView and the buttons, and not the containerView and the buttons? I think that's about the only difference I am sporting betwen your code and what I am doing via storyboard right now.Nighttime
I only realized after second reading that you are setting up a CONTAINERview and not a CONTENTview. Based on your code, I have recreated everything exactly in storyboard, and it is not scrolling. I'll edit my question with some screenshots.Nighttime
So it turns out my attempt to recreate the code in storyboard wasn't 100% correct. The trailing value for the last button should be exactly zero, mirroring H:|-[buttonA]-[buttonB]-[buttonC]-| which isn't very obvious when working in storyboard (or at least wasn't to me) but now after the fact seems trivial. I love autolayout but those little things get ya...Nighttime
What @Nighttime mentioned was an issue for me. My bottom view was a button and the bottom constraint was -32 by IB. I set that to 0 and it updated in IB to be Bottom Space to: superview. It will work, also it seems as long as you are on the positive side it works. Looks like that may be a bug with IB. Hope that helps someone else. I also removed all views and rewired which helps when trying to lay these out I find and it doesn't usually take long.Lilienthal
Y
8

There are so many questions about using AutoLayout with UIScrollView, the key point which we ignore is that the inner views of the UIScrollView make constraints against the Content View but not the UIScrollView itself. Refer to the Technical Note TN2154, you can find:

The UIScrollView class scrolls its content by changing the origin of its bounds. To make this work with Auto Layout, the top, left, bottom, and right edges within a scroll view now mean the edges of its content view.

The following figure will depicts that: enter image description here

You can find the trailing space is 500 points, if the constraint is made to the UIScrollView, the view will be miss placed and should be update its frame. However, no warnings and no errors. Because all the constraints are against the content view.

UIScrollView will calculate the size of the content view according to the constraints of the inner views. (For the example, the content size: width = 100(leading space) + 200 (view's width) + 500 (trailing space), height = 131 (top spacing) + 200(height) + 269(bottom spacing)

How to add constraints for views in the UIScrollView:

  1. Imaging the positions of views in the content view.
  2. Add top, right, bottom, left spacing to the edges of the content view, in addition, also the width and height of these views.

And all it is done.

An easy way to deal with AutoLayout with scrollview is to add a container view containing all subviews in the scroll view.

Conclusion: the key point to understand AutoLayout with UIScrollView is inner views make constraints against the content view but not UIScrollView itself.

attached example code

Youthful answered 22/9, 2014 at 14:30 Comment(0)
T
5

The following solution worked for me for scrollView with autolayout and without contentSize:

  1. Drag n drop a scrollView to viewController and apply whatever constraints to cover the space you want.
  2. Drag n drop a UIView inside the scrollView and make it cover the whole space of scrollView and apply constraints to be top, left, right, bottom space from scrollView.
  3. Set the height (and width if horizontal scrolling is required) of the inner view as per the need of scrolling. This part can also be done from code if required.
  4. Critical. After you set the height to some large value in point (3), go back to point (2) and be certain to set the top, left, right, bottom values back to zero as Xcode may have changed them for you when you force changed the height in (3).

And you're done. Now, you can add any number of controls on this view and apply the constraints relevant to each other (which don't seem working without this view). If you don't want to use this view then you'll have to apply constraints for each control related to scrollView (not related to each other).


The overwhelming tip..............

Critical. Let's say for clarity the UIScrollView is 1000 wide and 100 high. (In fact normally these values would be dynamic, of course, depending on the width of the device etc. But for now just say 1000 wide and 100 high.) Let's say you are doing a horizontal scroll. So put a UIView inside the UIScrollView. (That is the "content view".) Set all four constraints of the content view top, bottom, leading, trailing, to the scroll view. Make them all zero even if that seems wrong. Set the height of the content UIView to 100 and forget about that. Now: you want to scroll horizontally, so set the width of the content view to be let's say 1225.

Note that the width of the content view is now 225 bigger than the width of the parent scroll view. That's OK: in fact, you MUST do that. Note that

...you do NOT set the trailing width to negative 225...

you would think you have to "match" the widths as you normally would. But if you do that, it will not work at all.

You must set the leading and trailing numbers to ZERO, never negative (even though the width is "bigger")

Interestingly, you can actually set the leading/trailing numbers to any positive value (try say "50") and it gives you kind of a margin of the bounce. (It often looks great: try it.) Any negative value on either end will "silently break".

Note that, infuriatingly, often Xcode (as of 7.3.1 anyway),

will 'helpfully' set those values for you to negative numbers!

because it tries to automatically tally them for you. If so it will silently break. Set all four values to zero in the first instance. And set the width of the content view much wider than the "1000" in the example.


Edited: I've ended up with using UITableView instead of UIScrollView for most of my requirement. As tableView seems to me much more flexible and dynamic.

Tisiphone answered 4/6, 2015 at 13:47 Comment(1)
This is actually the best answer here. Thanks!Lezley
H
4

I assume you are running into issues with thecontentSize. Check out this blog post on how to handle the contentSize when using a "pure" AutoLayout approach. The gist of it is that your constraints implicitly define the content size. You NEVER set it explicitly when using AutoLayout. I've attached example project at the end of the blog post to demonstrate how it works

Hermineherminia answered 27/11, 2013 at 2:36 Comment(0)
M
3

There is a piece in the tech notes that you may have looked over. You can implicitly set the content size of a scroll view using constraints fixed to the edges of the scroll view.

Here's a simple example. Create a storyboard with one view, that has one scroll view. Set that scroll views constraints to make it fit the size of the view you put it in.

Inside that scroll view add a single view. Explicitly set the size of that view using constraints (and make sure that size is bigger than the scroll view).

Now add four more constraints to that inner view locking the four edges of the inner view to its parent scroll view. Those four constraints will cause the content size to expand to accommodate the inner view.

If you have multiple views you want to add to a scroll view, for example laid out horizontally, you'd lock the left side of the first subview to the left of the scroll view, lock the subviews to each other horizontally, and the right side of the last sub view to the right side of the scroll view. Those constraints would force the content size of the scroll view to expand to accommodate all of the subviews and their constraints.

Maturity answered 27/11, 2013 at 2:47 Comment(0)
C
3

If your question is "How do I put a bunch of UITextFields in a vertically scrolling UIScrollView such that they move out of the way of the keyboard when they have focus", the best answer is:

Don't.

Use a UITableViewController with static cells instead.

You get this scroll-out-of-the-way behaviour for free, AND all the content insets Just Work if your view controller is displayed inside a UINavigationController.

Compute answered 14/1, 2015 at 16:18 Comment(0)
G
3

You should organize your layout like this
ViewControllerView contains ScrollView, ScrollView contains ContainerView, ContainerView contains 2 Labels
enter image description here

Then follow 3 steps for make your ScrollView can scroll

  1. Setting ScrollView pin (top/right/bottom/left) to ViewControllerView
    • Setting ContainerView pin (top/right/bottom/left) to ScrollView
    • Set Horizontally in Container (don't set Vertically in Container)
    • Label1 pin (top/right/left) to ContainerView
    • Label1 pin (right/left/bottom) to ContainerView and top to Label1

enter image description here

HERE is the demo project

Hope this help

Glassco answered 5/7, 2016 at 10:29 Comment(0)
E
1

The pure autolayout approach works beautifully but it is quite a pain to get set up if you're migrating from non-autolayout. I've done it a few times now and I have a few general tips:

  • Start small: even if it means recreating your storyboard views, start with just a few elements and build your views slowly, making sure to test that scrolling works after adding a few elements.
  • Turn off translatesAutoresizingMaskIntoConstraints on everything: this was always the the cause of constraint conflicts for me.
  • Set your UIScrollView constraints properly: make sure the scroll view is connected on all sides to the parent view, otherwise it just won't expand at all.
Expander answered 27/11, 2013 at 2:28 Comment(0)
N
1

After some time dealing with this issue, I finally found a solution. I'm working with universal class sizes storyboards (600x600). I created a UIView (contentView) the size of the scrollView and created constraints to Top, Bottom, Leading and Trailing to the scrollView. Then I clipped the size manually of the contentView to 600x600. The storyboard stopped trying to resize everything and I could work but the view looked awful on the real device or simulator. I made 2 constraint outlets of this clipped sizes.

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contentViewWidthConstraint; 
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contentViewHeightConstraint;

Then in viewDidLoad

CGSize viewSize = self.view.frame.size;
self.contentViewWidthConstraint.constant = viewSize.width;
self.contentViewHeightConstraint.constant = viewSize.height;

Works great.

Nicholasnichole answered 26/1, 2015 at 13:41 Comment(0)
D
1

If like me you just use static content without counstraints inside the subview, like you can do like this:

override func viewDidLayoutSubviews() {
    scrollView.contentSize = CGSizeMake(320, 800)
}
Diamond answered 11/2, 2015 at 6:44 Comment(0)
F
1

I spent days trying to find a solution of how to use AutoLayout view an embedded Scrollview, to centre the scrollview in the visible screen, that works across all devices / screen dimensions as well as with screen rotation.

I spent days trying to do it with Autolayout only, and got close but never close enough. So in the end I had to add 3 lines of code per screen as well, in viewDidLoad.

See solution below :

  1. Create the scrollview and fill it with whatever objects you want
  2. Turn on auto layout
  3. Then Centre the ScrollView Vertically and Horizontally Centre ScrollView
  4. Select the View and then 'Add missing constraints' - this then does its thing
  5. The result is that the a lot of constraints are generated. There are 2 new ones created for the view : 'Horiz space scrollview to View' and 'Vert space scrollview to view' or vice-versa.
  6. Delete the 'Horiz space scrollview to View' so you are now left with 3 constraints on the View. The 2 for entering the scrollview in the view and the one to set a vertical space between the scrollview and the view
  7. Now link the Vert constraint to your code by click and Ctrl dragging it to the header file and creating an NSLayoutConstraint IBOutlet (I called mine constraintVertVtoSV)
  8. Now go to the .m file and add these lines of code into viewDidLoad (play with the padding amount to get the correct vert centering)

    if (IPAD)
    

    { self.constraintVertVtoSV.constant = 150.0; }

  9. this should now run on all devices and be properly centered and still scroll properly.

Frontpage answered 18/4, 2015 at 17:47 Comment(0)
G
1

Similar problem I'm having today with iOS 8.4, Xcode 6.4

There a view containing a scroll view, containing a contentView (UIView) containing subviews.

Everything is auto layout everywhere. The scrollview edges are pinned to the parent views edges with constraints. The content view edges are pinned to the scroll view edges with constraints.

Originally the content view would refuse to size as the full width of the scroll view. I had to add an additional constraint on the content view to have its width match the parent scroll view. Or I could set a contentView.centerX == scrollView.centerX constraint. Either one of those in addition to pinning the edges suddenly made the content view properly size.

// Either one of these additional constraints are required to get autolayout to correctly layout the contentView. Otherwise contentView size is its minimum required size
scrollView.addConstraint(NSLayoutConstraint(item: contentView, attribute: .CenterX, relatedBy: .Equal, toItem: scrollView, attribute: .CenterX, multiplier: 1.0, constant: 0))
scrollView.addConstraint(NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.Width, relatedBy: .Equal, toItem: scrollView, attribute: .Width, multiplier: 1.0, constant: 0.0))

Pinning the edges of the content view to the scroll view using visual constraints of the form,

let cvConstraints = ["H:|[contentView]|", "V:|[contentView]|"]

I use a routine to iterate through the array and add them to the scrollView.

Grory answered 4/8, 2015 at 3:45 Comment(0)
A
1

I faced a similar problem. I set every constrained and was always wondering why it still resizes some subviews. My solution was to set clipsToBounds to YES.

Aurangzeb answered 28/8, 2015 at 14:17 Comment(0)
S
1

In swift you can use this working solution.

Contraints

ScrollView: Leading, Trailing, Top, Bottom = Superview

ContentView: Leading, Trailing, Top, Bottom = ScrollView. Height fixed/relative to content.

You can set the width constraint(contentView) to equal scrollviews superview, but select remove remove on build time because you will be adding that constraint programmatically. This is just so the IB doesn't complain with warnings.

extension UIView {

    func setupContentViewForViewWithScroll(contentView vwContent : UIView) {
        //Set constraint for scrollview content
        let constraint = NSLayoutConstraint(item: vwContent, attribute: NSLayoutAttribute.Width, relatedBy: .Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: self.bounds.size.width)
        vwContent.addConstraint(constraint)
        self.layoutSubviews()
    }

}

And in the View Controller viewDidLayoutSubviews i just call this method:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    self.view.setupContentViewForViewWithScroll(contentView: vwContent)
}
Shortening answered 20/10, 2015 at 11:51 Comment(0)
D
0

I know this is a layman's solution and not what Apple suggests in the docu, but it worked for me twice, with different content and can be set up very quickly: In the storyboard view controller insert UIView. In UIView insert a Table View, Dynamic, 0 Prototype cells, Style Plain or Grouped. In Table View insert a Scroll View, in Scroll View insert content. Thats it, no settings in the custom view controller.

Derian answered 8/5, 2014 at 10:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.