UIViewController viewDidLayoutSubviews

18.8k views Asked by At

I am having difficulty figuring out why Erica Sadun does the following (calling viewDidAppear in viewDidLayoutSubviews) in her cookbook example Ch07-11. Perhaps the two methods should be calling another method instead?

See: https://github.com/erica/iOS-5-Cookbook/tree/master/C07

- (void) viewDidAppear:(BOOL)animated
{
    scrollView.frame = self.view.bounds;
    scrollView.center = CGRectGetCenter(self.view.bounds);

    if (imageView.image)
    {
        float scalex = scrollView.frame.size.width / imageView.image.size.width;
        float scaley = scrollView.frame.size.height / imageView.image.size.height;
        scrollView.zoomScale = MIN(scalex, scaley);
        scrollView.minimumZoomScale = MIN(scalex, scaley);
    }
}

- (void) viewDidLayoutSubviews
{
    [self viewDidAppear:NO];
}

Any idea why?

2

There are 2 answers

1
wakakaJP On

because layout srollView in viewDidLayoutSubviews will change scrollView which you had setted up.Then, scrolling scrollView should get little stutters.

0
Jared Egan On

This just seems flat out wrong to me. Let UIKit handle when these methods get called.

Do this instead:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated]; // Always call super with this!!!

    [self doSomeCustomLayoutStuff]; // I don't actually think this is necessary. viewWillLayoutSubviews is meant for laying out subviews, and gets called automatically in iOS 5 and beyond.

}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];

    [self doSomeCustomLayoutStuff];
}

- (void)doSomeCustomLayoutStuff {
    scrollView.frame = self.view.bounds;
    scrollView.center = CGRectGetCenter(self.view.bounds);

    if (imageView.image)
    {
        float scalex = scrollView.frame.size.width / imageView.image.size.width;
        float scaley = scrollView.frame.size.height / imageView.image.size.height;
        scrollView.zoomScale = MIN(scalex, scaley);
        scrollView.minimumZoomScale = MIN(scalex, scaley);
    }
}