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

Swift中如何通过代码实现视图控制器间的跳转?

完全懂你不想依赖Storyboard拖曳Segue的心情——纯代码实现视图控制器跳转不仅更灵活,对于包含表格视图这类复杂组件的VC来说,可控性也强得多。下面给你两种最常用的纯代码方案,适配你的场景:

1. 导航栈 Push 跳转(对应你原Segue的导航场景)

如果你的当前视图控制器是嵌入在UINavigationController中的(和你原代码里通过Segue跳转到导航包裹的VC逻辑一致),可以用这种方式:

@IBAction func newPostButtonAction(_ sender: UIButton) {
    // 实例化目标视图控制器
    let newPostVC = GMNewPostController()
    
    // 如果需要给目标VC传递数据,直接在这里赋值即可(比Segue的prepare方法更直观)
    // newPostVC.postTitle = "默认标题"
    // newPostVC.tableData = ["数据1", "数据2"]
    
    // 执行push跳转,加入导航栈
    navigationController?.pushViewController(newPostVC, animated: true)
}
2. 模态跳转(Modal Presentation)

如果不需要把目标VC加入导航栈,而是以弹出的方式展示(比如全屏弹窗),可以用这种方式。如果你的目标VC需要导航栏,也可以手动给它包裹一个UINavigationController:

@IBAction func newPostButtonAction(_ sender: UIButton) {
    let newPostVC = GMNewPostController()
    // 给目标VC包裹导航栏(可选,和你原代码里的逻辑匹配)
    let navWrapper = UINavigationController(rootViewController: newPostVC)
    
    // 设置模态展示样式(可选,比如全屏、卡片式等)
    navWrapper.modalPresentationStyle = .fullScreen
    
    // 执行模态跳转
    present(navWrapper, animated: true, completion: nil)
}

额外说明

  • 如果你的GMNewPostController是从XIB文件创建的,实例化时需要改成:
    let newPostVC = GMNewPostController(nibName: "GMNewPostController", bundle: nil)
    
  • 纯代码跳转的优势:不需要在Storyboard里配置Segue标识符,也避免了Storyboard的耦合问题,后续维护复杂VC结构时,代码逻辑会更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:32:49