Search code examples
iosxcodeuiscrollviewautolayoutpresentmodalviewcontroller

Scrollview in 'present modally' view controller not working


I have a view controller that is to be presented modally and in that VC I have a scrollview. However, adding a scrollview normally does not seem to work when my segue is of type 'present modally'. I read somewhere that I have to put my scrollview in another view for it to work. So this is my view hierarchy:

These are my constraints for view A:

ScrollView constraints:

ViewB constraints:

And in ViewB, I have another view which I have given a top, left & right constraint of 0 to its superview. I have set this in code as well:

 override func viewDidLayoutSubviews()
{
    viewB.frame.size.height = 2000
    scrollView.contentSize = viewB.frame.size
}

However, the scrollview still does not scroll. Thanks to anyone who can help out...been stuck on this for a while.


Solution

  • The problem is that you have given ViewB constraints to its containing scroll view. This is fine, if you're going to take that approach (which I prefer); but it means that the scroll view's contentSize is determined by ViewB's size, not by the contentSize property. Thus, your viewDidLayoutSubviews code is useless and your first move should be to throw it away.

    Now then, what is ViewB's size? Unfortunately, it's the same as the scroll view's size, because you have given ViewB width and height constraints that made it the same size as the scroll view. Therefore there is nothing to scroll.

    The solution is to do through constraints what you were trying to do in code, namely, give ViewB a height constraint that is fixed at 2000, instead of height constraint you have given it.