Search code examples
iosobjective-cuiviewuiscrollviewautolayout

How to scroll a UIScrollView to the bottom in viewWillAppear, when using autolayout,without a visual animation


Here is the problem:

I have a bunch of views that I put in a UIScrollView. The size and position of those subviews are defined by constraints. This works perfectly, and scrolling works too. So far so good.

However, I want my scrollview to scroll all the way to the bottom when I show the viewcontroller on screen for the first time, and this is where trouble starts. In order to know where the bottom is I need to know the position and size of the lowest element in my subviews. Should be easy too (since I have the reference to that UIView somewhere): get the frame of the UIView and voila.

I want to scroll the scrollview to the bottom before it appears on screen (so basically, in viewWillAppear:), but the constraints only get evaluated after viewWillAppear and before viewDidAppear: is called.

Getting the UIView frame in viewWillAppear gives me a zero sized CGRect. Doing the same in viewDidAppear gives me the correct CGRect. But viewDidAppear is too late for me, since the scrollview is on screen already so you see the content moving up.

Does anyone have a good solution for this? I tried putting the code in viewDidLayoutSubviews but that doesn't work either.


Solution

  • The solution I finally came up with was to:

    • Store all subviews of the scrollview in 1 contentview and not directly as child of the scrollview
    • observe when the bounds of that contentview change
    • each time they change do a scrollRectToVisible to the bottom of the scrollview
    • disable the auto-scroll-to-bottom as soon as a scrollViewWillBeginDragging delegate call is detected so the auto-scrolling stops when the user starts moving the scrollview