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

请问如何以最佳方式dismiss view controller?实现按钮触发的程序化关闭

嘿,这个问题我太熟了!要程序化关闭ViewController,核心得看你是怎么把这个VC展示出来的,最常见的两种场景我给你掰扯清楚:

1. 关闭模态弹出的ViewController

如果你的VC是通过present(_:animated:completion:)方法弹出来的,那直接在当前VC里调用dismiss方法就行,完全不用依赖导航栏按钮。比如给按钮绑定一个点击事件:

@IBAction func dismissButtonTapped(_ sender: UIButton) {
    // animated设为true会有平滑的过渡动画,false则直接关闭
    // completion可以传入一个闭包,用来处理关闭完成后的逻辑(比如刷新父VC的数据)
    self.dismiss(animated: true) {
        print("ViewController已经关闭啦")
    }
}

注意哦:如果你的按钮逻辑写在子视图或者其他类里,最好通过代理、闭包或者找到当前的presentingViewController来调用dismiss,尽量避免用全局的keyWindow方式,那样代码耦合度太高。

2. 从导航栈中移除当前ViewController(不用导航栏返回)

如果你的VC是被push到UINavigationController的栈里的,那可以用导航控制器的pop相关方法来返回:

@IBAction func goBackButtonTapped(_ sender: UIButton) {
    // 返回上一个ViewController
    self.navigationController?.popViewController(animated: true)
    
    // 要是想直接回到导航栈的根VC,用这个:
    // self.navigationController?.popToRootViewController(animated: true)
    
    // 甚至可以指定回到栈里的某个特定VC:
    // if let targetVC = self.navigationController?.viewControllers.first(where: { $0 is YourTargetVC }) {
    //     self.navigationController?.popToViewController(targetVC, animated: true)
    // }
}

这里要注意:调用前最好确认navigationController不是nil,不然会无响应(比如当前VC没被加入导航栈的话,navigationController就是nil)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:54:32