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

视图Dismiss操作未触发Completion函数,寻求技术解决方案

Why Your Dismiss Completion Isn't Firing

Hey there! Let's break down why that completion block in your dismiss call never runs, and how to fix it.

The Root Problem

Looking at your code:

@IBAction func tapBack(_ sender: Any) { 
    self.navigationController?.popViewController(animated: true) 
    self.dismiss(animated: true, completion: { print("this should print") }) 
}

You're calling both popViewController and dismiss in the same action. Here's what happens:

  • popViewController removes your current view controller from the navigation stack immediately (or as part of the animated transition).
  • By the time you call dismiss, your view controller is no longer part of the active view hierarchy—so the dismiss operation doesn't execute at all, which means its completion block never gets triggered.

Wrapping it in DispatchQueue.main.async doesn't help because the issue isn't about thread timing—it's about your view controller already being discarded when dismiss tries to run.

The Fixes

You need to pick the right method based on how your view controller was presented:

1. If your view controller was pushed onto the navigation stack

Use only popViewController. For iOS 16+, Apple added a completion handler directly to popViewController:

@IBAction func tapBack(_ sender: Any) {
    if #available(iOS 16.0, *) {
        navigationController?.popViewController(animated: true) {
            print("this should print")
        }
    } else {
        // For iOS versions before 16, use UINavigationControllerDelegate
        navigationController?.popViewController(animated: true)
        // Implement navigationController(_:didShow:animated:) in your delegate to detect when pop finishes
    }
}

2. If your view controller was presented modally

Use only dismiss—you don't need the popViewController call at all:

@IBAction func tapBack(_ sender: Any) {
    dismiss(animated: true) {
        print("this should print")
    }
}

Key Takeaway

Never mix popViewController and dismiss for the same view controller. Each method corresponds to a different way of presenting view controllers:

  • push ↔ popViewController
  • present ↔ dismiss

内容的提问来源于stack exchange,提问作者Andrew WC Brown

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:51:53