Instead of push segue how to replace view controller (or remove from navigation stack)?

前端 未结 14 903
眼角桃花
眼角桃花 2020-11-28 01:46

I have a small iPhone app, which uses a navigation controller to display 3 views (here fullscreen):

\"Xcode

14条回答
  •  臣服心动
    2020-11-28 02:26

    To expand on the various segues above, this is my solution. It has the following advantages:

    • Can work anywhere in the view stack, not just the top view (not sure if this is realistically ever needed or even technically possible to trigger, but hey it's in there).
    • It doesn't cause a pop OR transition to the previous view controller before displaying the replacement, it just displays the new controller with a natural transition, with the back navigation being to the same back navigation of the source controller.

    Segue Code:

    - (void)perform {
        // Grab Variables for readability
        UIViewController *sourceViewController = (UIViewController*)[self sourceViewController];
        UIViewController *destinationController = (UIViewController*)[self destinationViewController];
        UINavigationController *navigationController = sourceViewController.navigationController;
    
        // Get a changeable copy of the stack
        NSMutableArray *controllerStack = [NSMutableArray arrayWithArray:navigationController.viewControllers];
        // Replace the source controller with the destination controller, wherever the source may be
        [controllerStack replaceObjectAtIndex:[controllerStack indexOfObject:sourceViewController] withObject:destinationController];
    
        // Assign the updated stack with animation
        [navigationController setViewControllers:controllerStack animated:YES];
    }
    

提交回复
热议问题