You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用present跳转时,如何从A→D的视图控制器流程中移除B?

How to Remove ViewController B After Reaching D (Using Presented Modals)

Hey there, let's break this down for you. First, a quick reminder: when you use presentViewController to navigate between view controllers, each presented VC forms a modal stack (think of it as a chain where each VC sits on top of the last). Since you want to remove B after reaching D, I’m assuming your actual navigation flow is something like A → B → C → D (all presented modally)—if that’s not the case, I’ll cover that scenario too!

Instead of just presenting D directly from C, we’ll first strip out B and C from the stack, then have A present D directly. This ensures B is completely removed from the modal hierarchy.

Step 1: Navigate to D and Clean Up the Stack

In your CViewController, when you’re ready to present D, use this code to find the root A VC, dismiss the intermediate VCs, and present D:

// In CViewController
func goToD() {
    // Recursively find the root presenting VC (which is A)
    func findRootPresentingVC(from vc: UIViewController) -> UIViewController {
        guard let presentingVC = vc.presentingViewController else {
            return vc
        }
        return findRootPresentingVC(from: presentingVC)
    }
    
    let rootAVC = findRootPresentingVC(from: self)
    
    // Dismiss C and B first, then have A present D
    self.dismiss(animated: false) {
        let dVC = DViewController()
        rootAVC.present(dVC, animated: true, completion: nil)
    }
}

This way, once D is presented, the modal stack only contains A and D—B is gone for good.

If Your Flow Is A → D Directly

If you’re actually presenting D straight from A, but B is still hanging around in memory (maybe you presented B earlier and didn’t dismiss it), you’ll need to hold a reference to B in A to dismiss it:

// In AViewController
var bViewController: BViewController?

// When you originally presented B
func presentB() {
    let bVC = BViewController()
    bViewController = bVC
    present(bVC, animated: true)
}

// When presenting D, dismiss B first
func presentD() {
    bViewController?.dismiss(animated: false) { [weak self] in
        let dVC = DViewController()
        self?.present(dVC, animated: true)
    }
}

What to Avoid

Don’t try to directly modify UIKit’s private modal stack structure (like accessing hidden arrays of presented VCs). Apple doesn’t support this, and it can lead to weird bugs, memory leaks, or broken UI state. Stick to the public presentingViewController and dismiss APIs.

内容的提问来源于stack exchange,提问作者user9294044

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:36:37