iOS: different addSubview behavior between iOS 4.3 and 5.0

前端 未结 7 2030
长发绾君心
长发绾君心 2021-01-30 11:32

while coding in iOS 4.3 before, I found while add a view controller\'s view to another view with [superview addSubView:controller.view], the controller instance wil

7条回答
  •  鱼传尺愫
    2021-01-30 11:40

    In iOS 4 you had to manually call -viewWillAppear, -viewWillDisappear, etc. when adding or removing a view from your view hierarchy. These are called automatically in iOS 5 if the view is being added or removed from the window hierarchy. Fortunately, iOS 5 has a method in UIViewController that you can override to revert the behaviour back to how it worked with iOS 4. Just add this to your UIViewController:

    -(BOOL)automaticallyForwardAppearanceAndRotationMethodsToChildViewControllers {
       return NO;
    }
    

    This is probably the easiest solution as long as you're supporting both iOS 4 and iOS 5. Once you drop support for iOS 4 you might consider modifying your code to use the newer approach when swapping views.

    Edit 5 February 2012

    Apparently this function requires the child view controller be added to the main view controller using the addChildViewController: method. This method doesn't exist in iOS4, so you need to do something like this:

      if ([self respondsToSelector:@selector(addChildViewController:)] ) {
         [self addChildViewController:childViewController];
      }
    

    Thanks to everyone who corrected me on this.

提交回复
热议问题