Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 869
Joris Mans Avatar asked Jul 22 '14 22:07

Joris Mans


1 Answers

The problem with viewWillAppear is that it is called before the layout happens. You have to adjust the scroll view's content offset after it is laid out - in viewDidLayoutSubviews method. in Here is my solution:

@property (nonatomic, assign) BOOL shouldScrollToBottom;


- (void)viewDidLoad
{
    [super viewDidLoad];

    _shouldScrollToBottom = YES;
}


- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    // Scroll table view to the last row
    if (_shouldScrollToBottom)
    {
        _shouldScrollToBottom = NO;
        [_scrollView setContentOffset:CGPointMake(0, CGFLOAT_MAX)];
    }
}
like image 71
Rafa de King Avatar answered Nov 19 '22 10:11

Rafa de King