ChatGPT解决这个技术问题 Extra ChatGPT

UIScrollView not scrolling

I have a UIScrollView which contains many UIImageViews, UILabels, etc... the labels are much longer that the UIScrollView, but when I run the app, I cannot click and scroll down...

Why might this be?

Thanks

New 3/26/2013 I stumbled on an easier way to do this without code (setting contentSize) stackoverflow.com/a/15649607/1705353

R
Rohit Pathak

It's always good to show a complete working code snippet:

// in viewDidLoad (if using Autolayout check note below):

UIScrollView *myScrollView;
UIView *contentView;
// scrollview won't scroll unless content size explicitly set

[myScrollView addSubview:contentView];//if the contentView is not already inside your scrollview in your xib/StoryBoard doc

myScrollView.contentSize = contentView.frame.size; //sets ScrollView content size

Swift 4.0

let myScrollView
let contentView

// scrollview won't scroll unless content size explicitly set

myScrollView.addSubview(contentView)//if the contentView is not already inside your scrollview in your xib/StoryBoard doc

myScrollView.contentSize = contentView.frame.size //sets ScrollView content size

I have not found a way to set contentSize in IB (as of Xcode 5.0).

Note: If you are using Autolayout the best place to put this code is inside the -(void)viewDidLayoutSubviews method .


Don't forget to set myScrollView.delegate = self ALSO, if this still isn't working, the answer below this one has GREAT advice (go to your xib/StoryBoard and make sure "AutoLayout" is disabled). Pro-Tip: You can also include <UIScrollViewDelegate> in your .h file if you wish to do things like programmatically scroll your UIScrollView.
@AlbertRenshaw you should have added an answer so I could have given you a +1 :) AutoLayout was the issue with me....drove me insane for like 4 hours.
Putting code in viewDidLayoutSubviews made it work for me.
For me the issue was that it didn't need to scroll, as everything fit on the screen.
u
user1539652

If you cannot scroll the view even after you set contentSize correctly, make sure you uncheck "Use AutoLayout" in Interface Builder -> File Inspector.


Alternatively, you can set contentSize in viewDidLayoutSubviews:, and it will be applied after the autolayout completes.
@" Chris Vasselli" slove my issue.. GR8..:-)
Chris' comment should be a separate answer!
Thank you so much Chris Vasselli! With Auto Layout enabled, it won't work in viewDidLoad but it does with viewDidLayoutSubviews!
Woah, I never noticed all these comments before! Glad I could help so many of you out! I just posted a separate answer so hopefully it will be easier to find.
J
Jose Llausas

You need to set the contentSize property of the scroll view in order for it to scroll properly.

If you're using autolayout, you need to set contentSize in viewDidLayoutSubviews in order for it to be applied after the autolayout completes.

The code could look like this:

-(void)viewDidLayoutSubviews
{
    // The scrollview needs to know the content size for it to work correctly
    self.scrollView.contentSize = CGSizeMake(
        self.scrollContent.frame.size.width,
        self.scrollContent.frame.size.height + 300
    );
}

Thanks a tonne.. This worked because for some reason, even when I set the value of contentSize to the size of contentView, the size of scrollView and contentView seems to get set as the same. But setting height of the contentSize to a value greater than the height of contentView, it worked.
viewDidLayoutSubviews can get called multiple times during a lifecycle so you run the risk increasing the height larger than expected.
@anon_nerd just check if it was called already and only add height if not
J
Jasper Blues

The answer above is correct - to make scrolling happen, it's necessary to set the content size.

If you're using interface builder a neat way to do this is with user defined runtime attributes. Eg:

https://i.stack.imgur.com/EFkqw.png


this didn't do anything for me.
Oops, the pic shows {0, 0}, but you of course have to put large enough numbers in. . . this approach will only work for simple views where you know the content-size up front. . . (in fact, for complex views I recommend pure code, anyway).
Much less hacky than doing it programmatically. Thank you!
@JakeStoeffler welcome! :) When using IB, I like to keep all the config there (not fragmented). But when things get complex (reusable view widgets; model adapters, layer manipulations; CAAnimations, etc) then I prefer fully programmatic views. . . more fluent.
I tried this, works when view appears, but on orientation change, the contentSize defined on the screen above is ignored and my log says the contentSize is set back 0,0. Any idea how to fix that?
A
Alex Zavatone

Try to resize the content size to huge numbers. I couldn't understand why my scroll view doesn't scroll even when its content size seems to be bigger than control size. I discovered that if the content size is smaller than needed, it doesn't work also.

self.scrollView.contentSize = CGSizeMake(2000, 2000);

Instead of 2000 you can put your own big numbers. And if it works, it means that your content size is not big enough when you resize.

The delegate is not necessary for scroll view to work.


Genius - such a simple way to check what is going on. Thanks a bunch!
B
Ben Gottlieb

Make sure you have the contentSize property of the scroll view set to the correct size (ie, one large enough to encompass all your content.)


do I have to do this programatically? or can I do it in IB?
If you're using IB, you can set it from there - see below. . (Separate answer, so I can include pics).
G
Gaurav Kumkar

Uncheck 'Use Autolayout' did the trick for me.

Environment: xCode 5.0.2 Storyboards ios7


d
devios1

In my case I had to set delaysContentTouches to true because the objects inside the scrollView were all capturing the touch events and handling themselves rather than letting the scrollView itself handle it.


I've the same issue. The problem for me is that by turning delaysContentTouches to true, you will end with lower quality drawings with an apple pencil. But this is a edge case :) in most cases it solve the issue
K
Kuldeep

Set contentSize property of UIScrollview in ViewDidLayoutSubviews method. Something like this

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    scrollView.contentSize = CGSizeMake(view.frame.size.width, view.frame.size.height)
}

A
Atef

The idea of why scroll view is not scrolling because you set the content size for scrolling less than the size of the scroll view, which is wrong. You should set the content size bigger than the size of your scroll view to navigate through it while scrolling.

The same idea with zooming, you set the min and max value for zooming which will applied through zooming action.

welcome :)


A
Abhinav Singh

One small addition, all above are the actual reasons why your scroll view might not be scrolling but sometimes mindlessly this could be the reason specially when scrollview is added through code and not IB, you might have added your subviews to the parent view and not to the scrollview this causes the subview to not scroll

and do keep the content size set and bigger than parent view frame (duhh!!)


M
Michele Dall'Agata

I made it working at my first try. With auto layout and everything, no additional code. Then a collection view went banana, crashing at run time, I couldn't find what was wrong, so I deleted and recreated it (I am using Xcode 10 Beta 4. It felt like a bug) and then the scrolling was gone. The Collection view worked again, though!

Many hours later.. this is what fixed it for me. I had the following layout:

UIView

Safe Area

Scroll view Content view

Content view

It's all in the constraints. Safe Area is automatically defined by the system. In the worst case remove all constraints for scroll and content views and do not have IB resetting/creating them for you. Make them manually, it works.

For Scroll view I did: Align Trailing/Top to Safe Area. Equal Width/Height to Safe area.

For Content view I did: Align Trailing/Leading/Top/Bottom to Superview (the scroll view)

basically the concept is to have Content view fitting Scrollview, which is fitting Safe Area.

But as such it didn't work. Content view missed the height. I tried all I could and the only one doing the trick has been a Content view height created control-dragging Content view.. to itself. That defined a fixed height, which value has been computed from the Size of the the view controller (defined as freeform, longer than the real display, to containing all my subviews) and finally it worked again!


You're very welcome! I know exactly how you felt.. ;-)
Thaaaaks, I spent a lot of hours and this solved my issue
K
Kuldeep

if you are getting a message (IOS8 / swift) that viewDidLayoutSubviews does not exist, use the following instead

override func viewDidAppear(animated: Bool)

This fixed it for me


H
Henry Heleine

My issue was resolved by:

setting the contentSize on the scrollView to a large height BUT also I had to fix top and/or bottom constraints on views within the scrollView, which meant the scroll indicators showed on screen but the content did not scroll

Once I removed top and/or bottom constraints bound to the safe area and/or superview, the views inside the scrollView could scroll again and didn't stay fixed to the top of bottom of the screen!

Hope this stops someone else from hours of pain with this particular issue.


Thank you for this!! I was using a horizontal scrollview and my leading constraint of the first subview was constrained to the superview's leading anchor - not the scrollview's leading anchor.
A
Anton Tropashko

yet another fun case:

scrollview.superview.userInteractionEnabled must be true

I wasted 2+hrs chasing this just to figure out the parent is UIImageView which, naturally, has userInteractionEnabled == false


Same case! you're a lifesaver. thanks a bunch!
yrw. even with cases like this its easier on ones nerves than programming droids
Right said. However, in my case, I had a UIScrollview inside a custom .xib based UIView subclass which was added on top of a UIImageView, which in turn, was a subview of a UIViewController's view, So I would hardly guess it was something to do with the UIImageView. :)
c
coolcool1994

Something that wasn't mentioned before!

Make sure your outlet was correctly connected to the scrollView! It should have a filled circle, but even if you have filled circle, scrollView may not been connected - so double check! Hover over the circle and see if the actual scrollview gets highlighted! (This was a case for me)

//Connect below well to the scrollView in the storyBoard
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

f
flo527

Alot of the time the code is correct if you have followed a tutorial but what many beginners do not know is that the scrollView is NOT going to scroll normally through the simulator. It is suppose to scroll only when you press down on the mousepad and simultaneously scroll. Many Experienced XCode/Swift/Obj-C users are so use to doing this and so they do not know how it could possibly be overlooked by beginners. Ciao :-)

@IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(scrollView)
    // Do any additional setup after the view
}

override func viewWillLayoutSubviews(){
    super.viewWillLayoutSubviews()
    scrollView.contentSize = CGSize(width: 375, height: 800)
}

This code will work perfectly fine as long as you do what I said up above


K
Kuldeep

Add the UIScrollViewDelegate and adding the following code to the viewDidAppear method fixed it for me.

@interface testScrollViewController () <UIScrollViewDelegate>

-(void)viewDidAppear:(BOOL)animated {
    self.scrollView.delegate = self;
    self.scrollView.scrollEnabled = YES;
    self.scrollView.contentSize = CGSizeMake(375, 800);
}

D
Dharmesh Dhorajiya

If none of the other solutions work for you, double check that your scroll view actually is a UIScrollView in Interface Builder.

At some point in the last few days, my UIScrollView spontaneously changed type to a UIView, even though its class said UIScrollView in the inspector. I'm using Xcode 5.1 (5B130a).

You can either create a new scroll view and copy the measurements, settings and constraints from the old view, or you can manually change your view to a UIScrollView in the xib file. I did a compare and found the following differences:

Original:

<scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" directionalLockEnabled="YES" bounces="NO" pagingEnabled="YES" showsHorizontalScrollIndicator="NO" showsVerticalScrollIndicator="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Wsk-WB-LMH">
...
</scrollView>

After type spontaneously changed:

<view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" customClass="UIScrollView" id="qRn-TP-cXd">
...
</view>

So I replaced the <view> line with my original <scrollView> line.

I also replaced the view's close tag </view> with </scrollView>.

Be sure to keep the id the same as the current view, in this case: id="qRn-TP-cXd".

I also had to flush the xib from Xcode's cache by deleting the app's derived data:

Xcode->Window->Organizer->Projects, choose your project, on the Derived Data line, click Delete...

Or if using a device:

Xcode->Window->Organizer->Device, choose your device->Applications, choose your app, click (-)

Now clean the project, and remove the app from the simulator/device:

Xcode->Product->Clean

iOS Simulator/device->press and hold the app->click the (X) to remove it

You should then be able to build and run your app and have scrolling functionality again.

P.S. I didn't have to set the scroll view's content size in viewDidLayoutSubviews or turn off auto layout, but YMMV.


C
Chase Roberts

If your scrollView is a subview of a containerView of some type, then make sure that your scrollView is within the frame or bounds of the containerView. I had containerView.clipsToBounds = NO which still allowed me see the scrollView, but because scrollView wasn't within the bounds of containerView it wouldn't detect touch events.

For example:

containerView.frame = CGRectMake(0, 0, 200, 200);
scrollView.frame = CGRectMake(0, 200, 200, 200);
[containerView addSubview:scrollView];
scrollView.userInteractionEnabled = YES;

You will be able to see the scrollView but it won't receive user interactions.


J
Jagat Dave

adding the following code in viewDidLayoutSubviews worked for me with Autolayout. After trying all the answers:

- (void)viewDidLayoutSubviews
{
    self.activationScrollView.contentSize = CGSizeMake(IPHONE_SCREEN_WIDTH, 620);

}

//set the height of content size as required

W
Wissa

The straightforward programmatically way

To wrap it up

Create a UIScrollView

private lazy var scrollView: UIScrollView = {
    let scrollView = UIScrollView()
    scrollView.translatesAutoresizingMaskIntoConstraints = false

    return scrollView
}()

Use a Single Child View to Hold All of Your Content Subviews

private lazy var contentView: UIView = {
    let view = UIView()
    view.translatesAutoresizingMaskIntoConstraints = false

    return view
}()

Add your views

contentView.addSubview(firstSubView)
contentView.addSubview(lastSubView)
scrollView.addSubview(contentView)
view.addSubview(scrollView)

Usually, you only want your content to scroll in one direction. In most cases to scroll vertically. Therefore set the width of the content view to be the width of the scroll view.

NSLayoutConstraint.activate([
    contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)

Attach four constraints (top, bottom, left, right) from our single content view to the scroll view.

    contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
    contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
    contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
    contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),

Make sure you have constraints attached to all four sides of the content view so that it will expand to the size of your content.

// After Adding your subviews to the contentView make sure you've those two constraints set:

    firstSubView.topAnchor.constraint(equalTo: contentView.topAnchor),
    .
    .
    .
    lastSubView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
])

Reference: Using UIScrollView with Auto Layout in iOS


H
H. de Jonge

After failing with the provided answers in this thread, I stumbled upon this article with the solution.

There are two things not intuitive about setting up the scrollview with autolayout:

The constraints you set up as margin between the contentview and scrollview do not influence the size of the contentview. They really are margins. And to make it work, the contentview should have a fixed size. The trick to the fixed size is that you can set the width of the contentview equal to that of the scrollview's parent. Just select both views in the tree on the left and add the equal widths constraint.

This is the gist of that article. For a complete explanation, including illustrations, check it out.


@PredragManojlovic How can it get more general than this? This is the only way I could get the scrollview to get to work properly, using auto-layout.
K
Kuldeep

I found that with this AutoLayout issue... if I just make the ViewController use UIView instead of UIScrollView for the class... then just add a UIScrollView myself... that it works.


N
Nandu

I had the same issue in IB.

After setting the leading, trailing, top and bottom of the scrollView to its superView. I made the following changes to make the containerView scrollable, which worked.

To make the scrollView only scroll on horizontal direction make the constraint with scrollView's centerY = ContainerView's centerY

and to make it vertically scrollable make the scrollView's centerX = ContainerView's centerX


b
bobby123uk

You don’t have to set the content size of the scroll view.

Technical Note TN2154


B
Benjamin

In case someone made the same mistake like me, I'd like to share my case.

In my case, I mistakenly add a constraint to one of the subviews of scrollview which makes the subview's space to the topLayoutGuide fixed, thus it's location can't be changed, so the scrollview can't be scrolled.