我希望在应用程序打开时立即运行条件if语句。基本上,它将是
if x = true {
//segue to viewcontroller1
} else {
//stay on this page
}
这将在Xcode中并以swift编码(显然语法错误)...如果条件为真,则将语法写入segue到特定视图控制器的适当方法是什么,并保持正常的方式打开应用程序后打开了吗?另外,我在哪里放这个?我通常在第一次显示的viewcontroller中考虑了viewdidload方法,但是在视图加载之前需要检查变量,这样如果条件为真且那个,视图就会变为另一个变量。首先打开?
编辑:我尝试按如下方式设置AppDelegate.swift
中的代码:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if x{
let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil)
let ViewController = mainStoryBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = ViewController
} else{
//same code as above but to different VC
}
return true
}
但是当我运行这个时,我在appDelegate中得到一个错误,说" libc ++ abi.dylib:以NSException类型的未捕获异常终止"。修改此代码的正确方法是什么?
答案 0 :(得分:3)
如果要在演示前选择场景。您可以在appDelegate.swift
中的application(application: UIApplication, didFinishLaunchingWithOptions)
中添加以下内容:
var id = x ? "id1" : "id2"
self.window = UIWindow(frame: UIScreen.main.bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let exampleVC: UIViewController = mainStoryboard.instantiateViewController(withIdentifier: id) as UIViewController
self.window?.rootViewController = exampleVC
self.window?.makeKeyAndVisible()
确保在故事板中命名场景
如果您在第一个场景显示然后选择要进行调整时表现良好:
if x {
self.performSegue(withIdentifier: "id1", sender: self)
} else {
self.performSegue(withIdentifier: "id2", sender: self)
}
再次确保在故事板中命名segues
另一种选择,使用UINavigationController
。将导航控制器设置为根视图控制器
let id = x ? "id1" : "id2"
let mainStoryboard = UIStoryboard(name: "MainStoryboard", bundle: nil)
let exampleVC = mainStoryboard.instantiateViewController(withIdentifier: id) as UIViewController
let navigationController = UINavigationController(rootViewController: exampleVC)
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window!.rootViewController = navigationController
self.window!.makeKeyAndVisible()