macOS开发中使用Swift/Storyboard如何在同一窗口切换视图控制器?
解决视图切换时同一窗口替换旧视图的方法
Storyboard 配置方案
- 首先确认你创建的segue类型,不要选择
Present Modally,这类segue本身的设计就是模态弹出新窗口,优先选择Show (e.g. Push)类型的segue - 给初始视图控制器套上导航控制器容器:选中初始视图控制器 → 顶部菜单栏
Editor→Embed In→Navigation Controller,套入后Show类型的segue会默认将新视图推入当前导航栈,不会弹出独立窗口 - 如果不需要保留旧视图,可在新视图的
viewDidAppear方法中手动移除导航栈里的旧视图 - 若不需要导航栏,也可以将segue的
Presentation属性设置为Current Context/Over Current Context,不要使用默认的Automatic/Full Screen,后两个属性会强制触发模态弹出逻辑
编程实现方案
基于导航控制器替换(保留导航交互能力)
// Swift 示例 let newVC = storyboard?.instantiateViewController(withIdentifier: "目标视图控制器的ID") as! 目标视图控制器类 navigationController?.pushViewController(newVC, animated: true) // 推入完成后移除旧视图 if let oldIndex = navigationController?.viewControllers.firstIndex(of: self) { navigationController?.viewControllers.remove(at: oldIndex) }
直接替换根视图(完全无旧视图残留)
// Swift 示例 let newVC = storyboard?.instantiateViewController(withIdentifier: "目标视图控制器的ID") as! 目标视图控制器类 // 替换当前窗口的根视图,可自定义过渡动画 UIView.transition(with: UIApplication.shared.windows.first!, duration: 0.3, options: .transitionCrossDissolve, animations: { UIApplication.shared.windows.first?.rootViewController = newVC }, completion: nil)
子视图局部替换
// Swift 示例,仅替换当前视图控制器下的子视图区域 children.forEach { $0.removeFromParent() } view.subviews.forEach { $0.removeFromSuperview() } let newVC = 目标视图控制器类() addChild(newVC) newVC.view.frame = view.bounds view.addSubview(newVC.view) newVC.didMove(toParent: self)
内容的提问来源于stack exchange,提问作者8-Bit Cat
相关产品推荐
相关产品推荐

