Olie
Olie

Reputation: 24675

When re-creating a UIViewcontroller's view, how do I force the rotation?

I have a view-controller that I'm re-using (for memory limitation reasons.) So, rather than push a new UIViewController, I just set a few parameters, then force this VC to reload its view. The code is something like this (triggered by a Notification callback):

- (void) reloadView: (NSNotification*) note
{
    // Save parameters for reloaded view
    UIWindow *window = (UIWindow*) self.view.superview;
    //CGAffineTransform xfrm = self.view.transform;  // Doesn't do what I want.

    // Trash this one & reload the view
    [self.view removeFromSuperview];
    self.view = nil;

    // force view reload
    if (self.view == nil)
    {
        NSLog(@"%s ***** Why didn't self.view reload?!", __PRETTY_FUNCTION__);
    }
    else
    {
        // restore params
        //self.view.transform = xfrm;  // Boo-hoo!
        [window addSubview: self.view];
    }
}

Everything works fine except that the app is landscape only, and the newly reloaded view is added to the Window as portrait.

I tried forcing the old view's transform onto the new view but, oddly, it gave the rotation but a goofy translation offset.

Is there a way to tell a UIViewController "do your rotation, now"...?

EDIT:

I added this rather silly hack:

    // restore params
    self.view.transform = xfrm;
    self.view.center = CGPointMake(window.bounds.size.width / 2., window.bounds.size.height / 2.);
    [window addSubview: self.view];

which gives the desired result, but I'm really displeased with having such a thing in my code base. Surely there's a better way to do this?!?!

Thanks!

EDIT:

After some discussion with JPH, then answer turned out to be "don't do things that way." See comments for some of the details and the redesign that took place.

Upvotes: 0

Views: 265

Answers (1)

JP Hribovsek
JP Hribovsek

Reputation: 6707

Your problem is in using this:

[window addSubview: self.view];

From the documentation:

If you add an additional view controller's UIView property to UIWindow (at the same level as your primary view controller) via the following:

[myWindow addSubview:anotherController.view];

this additional view controller will not receive rotation events and will never rotate. Only the first view controller added to UIWindow will rotate.

https://developer.apple.com/library/ios/#qa/qa2010/qa1688.html

I would much prefer a design with a root view controller and the subviews being added to the root view controller's view.

Another option is to NOT kill the view and re-add it, but rather update everything that needs to be updated in that view. I am not sure I understand why you would want to kill a view and re-add it right away.

Upvotes: 3

Related Questions