Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an iOS method that fires when Autolayout has completed?

I have an iOS app in which I need to know when a new view is completely visible on-screen; that is, when Autolayout has finished its calculations and the view has finished drawing.

ViewDidAppear seems to fire well before the view is completely visible. If I turn off Autolayout, the timing seems to line up as far as human perception goes, but I need to use Autolayout in this project (so this isn't a solution...just a test).

Is there any method that fires when Autolayout is done calculating? Or another method that fires when the view is ACTUALLY visible (since ViewDidAppear doesn't work for this)?

Thanks!

like image 214
Kent Avatar asked May 09 '14 01:05

Kent


3 Answers

The following can be used to avoid multiple calls:

- (void) didFinishAutoLayout {

    // Do some stuff here.    

    NSLog(@"didFinishAutoLayout");
}

and

- (void) viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];


    [NSObject cancelPreviousPerformRequestsWithTarget:self
                                 selector:@selector(didFinishAutoLayout)
                                           object:nil];
    [self performSelector:@selector(didFinishAutoLayout) withObject:nil
               afterDelay:0];
}
like image 82
Matt Avatar answered Nov 09 '22 01:11

Matt


I'm using viewDidLayoutSubviews for this. Apple's documentation says, "Called to notify the view controller that its view has just laid out its subviews."

like image 22
Gallymon Avatar answered Nov 09 '22 01:11

Gallymon


If you watched 2018's WWDC about "High-Performance AutoLayout", you would know the answer to this question.

Technically, there is no such API method that will be called when autolayout has completed your view's layout. But when autolayout has completed the calculations, your view's setBounds and setCenter will be called so that your view gets its size and position.

After this, your view's layoutSubviews will be called. So, layoutSubviews can, to some degree, be thought of as the method that fires after autolayout has done calculations.

As to view controller's viewDidLayoutSubviews, this is a bit complicated. The documentation says:

When the bounds change for a view controller's view, the view adjusts the positions of its subviews and then the system calls this method. However, this method being called does not indicate that the individual layouts of the view's subviews have been adjusted. Each subview is responsible for adjusting its own layout.

So when viewDidLayoutSubviews called on a view controller, only the view controller'view 's first-level subviews are guaranteed to be laid out correctly.

like image 2
Jiang Wang Avatar answered Nov 09 '22 00:11

Jiang Wang