Ios 使用if-else条件语句在Xcode/swift中显示特定的viewcontroller
我希望在应用程序打开时立即运行条件if语句。基本上是这样Ios 使用if-else条件语句在Xcode/swift中显示特定的viewcontroller,ios,iphone,swift,xcode,Ios,Iphone,Swift,Xcode,我希望在应用程序打开时立即运行条件if语句。基本上是这样 if x = true { //segue to viewcontroller1 } else { //stay on this page } 这将是在Xcode和swift编码(显然语法是错误的)。。。如果条件为真并保持在打开应用程序时通常打开的状态,那么编写语法以切换到特定视图控制器的适当方式是什么?还有,我把这个放在哪里?我在通常情况下第一次显示的viewcontroller中考虑了viewdidload方法,但是在加载视
if x = true {
//segue to viewcontroller1
} else {
//stay on this page
}
这将是在Xcode和swift编码(显然语法是错误的)。。。如果条件为真并保持在打开应用程序时通常打开的状态,那么编写语法以切换到特定视图控制器的适当方式是什么?还有,我把这个放在哪里?我在通常情况下第一次显示的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类型的未捕获异常终止”。修改此代码的正确方法是什么
appDelegate.swift
中的应用程序(应用程序:UIApplication,didFinishLaunchingWithOptions)
中添加以下内容:
确保在情节提要中命名场景if x {
self.performSegue(withIdentifier: "id1", sender: self)
} else {
self.performSegue(withIdentifier: "id2", sender: self)
}
同样,请确保在情节提要中命名片段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()
我为这个问题添加了一个编辑(尽管我很久以前就问过)。我想使用你的第一种方法,但我尝试了,并得到了错误,我张贴在上面。你能看一看我该如何修改代码吗?做了一些修改,希望对你有所帮助如果你对上面的内容感到困惑,请看以下内容:
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()