1 - (void)replaceViewController:(UIViewController *)existingViewController withViewController:(UIViewController *)newViewController inContainerView:(UIView *)containerView completion:(void (^)(void))completion 2 { 3 // Add initial view controller 4 if (!existingViewController && newViewController) { 5 [newViewController willMoveToParentViewController:self]; 6 [newViewController beginAppearanceTransition:YES animated:NO]; 7 [self addChildViewController:newViewController]; 8 newViewController.view.frame = containerView.bounds; 9 [containerView addSubview:newViewController.view]; 10 [newViewController didMoveToParentViewController:self]; 11 [newViewController endAppearanceTransition]; 12 if (completion) completion(); 13 } 14 // Remove existing view controller 15 else if (existingViewController && !newViewController) { 16 [existingViewController willMoveToParentViewController:nil]; 17 [existingViewController beginAppearanceTransition:NO animated:NO]; 18 [existingViewController.view removeFromSuperview]; 19 [existingViewController removeFromParentViewController]; 20 [existingViewController didMoveToParentViewController:nil]; 21 [existingViewController endAppearanceTransition]; 22 if (completion) completion(); 23 } 24 // Replace existing view controller with new view controller 25 else if ((existingViewController != newViewController) && newViewController) { 26 [newViewController willMoveToParentViewController:self]; 27 [existingViewController willMoveToParentViewController:nil]; 28 [existingViewController beginAppearanceTransition:NO animated:NO]; 29 [existingViewController.view removeFromSuperview]; 30 [existingViewController removeFromParentViewController]; 31 [existingViewController didMoveToParentViewController:nil]; 32 [existingViewController endAppearanceTransition]; 33 [newViewController beginAppearanceTransition:YES animated:NO]; 34 newViewController.view.frame = containerView.bounds; 35 [self addChildViewController:newViewController]; 36 [containerView addSubview:newViewController.view]; 37 [newViewController didMoveToParentViewController:self]; 38 [newViewController endAppearanceTransition]; 39 if (completion) completion(); 40 } 41 }
时间: 2024-09-19 14:55:08