根据条件加载不同的 storyboard
项目启动时,根据条件加载不同的 storyboard,或加载 storyboard 中的不同 ViewController
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
var vc: UIViewController!
if true {
vc = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
} else {
vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Storyboard ID")
}
window?.rootViewController = vc
window?.makeKeyAndVisible()
return true
}
用 instantiateInitialViewController
方法,就会进 storyboard 中初始箭头所指的界面。

注意 withIdentifier 后跟的是 viewController 的 storyboard ID 而不是类名。
多个 Storyboard
storyboard 里界面多了后,操作起来会不太方便,可以使用多个 storyboard,进行模块化。
按住 command 选中要提到第二个 storyboard 的 viewController,Xcode 顶部菜单 Editor->Refactor to Storyboard...

弹出框中输入 storyboard 名字

在原.storyboard 文件中出现一个 Storyboard Reference,双击跳到新文件,可看到刚才选中的 View Controller 都在新 .storyboard 文件中。

也可以手动添加 Storyboard Reference,手动创建.storyboard 文件,在 Storyboard Reference 的属性中设置文件名,就关联起来了。


使用 storyboard 时页面传值
注意设置 segue 的 id

class MainController: UIViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case "segueid":
let vc = segue.destination as! MainController
vc.x = 99 // 传值
default:
break
}
}
}
网友评论