iPhone - dismiss multiple ViewControllers

后端 未结 22 3110
粉色の甜心
粉色の甜心 2020-11-28 04:46

I have a long View Controllers hierarchy;

in the first View Controller I use this code:

SecondViewController *svc = [[SecondViewController alloc] i         


        
22条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 05:33

    iOS 8+ universal method for fullscreen dismissal without wrong animation context. In Objective-C and Swift

    Objective-C

    - (void)dismissModalStackAnimated:(bool)animated completion:(void (^)(void))completion {
        UIView *fullscreenSnapshot = [[UIApplication sharedApplication].delegate.window snapshotViewAfterScreenUpdates:false];
        [self.presentedViewController.view insertSubview:fullscreenSnapshot atIndex:NSIntegerMax];
        [self dismissViewControllerAnimated:animated completion:completion];
    }
    

    Swift

    func dismissModalStack(animated: Bool, completion: (() -> Void)?) {
        if let fullscreenSnapshot = UIApplication.shared.delegate?.window??.snapshotView(afterScreenUpdates: false) {
            presentedViewController?.view.addSubview(fullscreenSnapshot)
        }
        if !isBeingDismissed {
            dismiss(animated: animated, completion: completion)
        }
    }
    

    tl;dr

    What is wrong with other solutions?

    There are many solutions but none of them count with wrong dismissing context so:

    e.g. root A -> Presents B -> Presents C and you want to dismiss to the A from C, you can officialy by calling dismissViewControllerAnimated on rootViewController.

     [[UIApplication sharedApplication].delegate.window.rootViewController dismissModalStackAnimated:true completion:nil];
    

    However call dismiss on this root from C will lead to right behavior with wrong transition (B to A would have been seen instead of C to A).


    so

    I created universal dismiss method. This method will take current fullscreen snapshot and place it over the receiver's presented view controller and then dismiss it all. (Example: Called default dismiss from C, but B is really seen as dismissing)

提交回复
热议问题