IOS - 如何在不同场景中的viewControllers之间跳转

时间:2017-02-15 10:30:03

标签: ios swift uiviewcontroller navigation

我有5个viewControllers(A,B,C,D,E),所有这些viewControllers都是以编程方式连接的,我可以成功地在它们之间推送和弹出。

使用:

   navigationController?.pushViewController(loginVc, animated: true)
_ = navigationController?.popViewController(animated: true)

注意: ViewController A首先显示为默认的初始viewController。

现在,我想要的是,当用户安装App时,只有第一次viewController A必须显示为初始viewController,其余时间打开App时,viewController D必须是初始值viewController,从那里我应该能够在以前的viewControllers之间跳转。我该如何实现呢。我正在使用Xcode 8.2,Swift 3.0

提前致谢。

6 个答案:

答案 0 :(得分:3)

为了做到这一点,您只需使用以下代码向NSUserDefaults添加布尔值:

    let defaults = UserDefaults.standard
    if (!defaults.bool(forKey: "firstTime")) { //will be false if does not exist yet
         navigationController?.pushViewController(yourDesiredVC, animated: true) //push desired vc
         defaults.set(true, forKey: "firstTime") //set the key so it never executes again
   } else {
       navigationController?.pushViewController(yourDesiredVC, animated: true) //push the other vc  
   }

答案 1 :(得分:2)

如果没有一些代码,你的问题并没有真正说明,但是一个建议(考虑到问题的当前质量)将使用UserDefaults。将您当前版本的应用添加到名为例如LatestVersion。在启动时将其与应用当前版本进行比较,如果它们不匹配,则显示ViewControllerA,如果不显示ViewControllerB

另一种方法是保存launchedForFirstTime。如果未设置显示ViewControllerA,则上述内容会考虑您可能希望展示该视图的应用的未来版本。

答案 2 :(得分:2)

您可以在UserDefaults中保留一个值,以跟踪返回的用户并检查它是否在那里:

 if let returning :Bool = UserDefaults.standard.bool(forKey: "initial_controller_shown") {
    //returning user flow
   }  else {
    //new user flow
   }

检查此问题的常见位置是applicationDidBecomeActive或didFinishLaunchingWithOptions

答案 3 :(得分:2)

当你的应用第一次启动时,然后使用一个标志并在其中存储一些值,以便下次当你的应用运行时,你可以检查用户是否第一次访问应用程序..现在之后转到appDelegate并将以下代码粘贴到DidFinishLaunchingWithOption ...

if yourFlag == true
{     
let mainStoryboard: UIStoryboard = UIStoryboard(name: "MainStoreyBoard", bundle: nil)
     let controller = mainStoryboard.instantiateViewController(withIdentifier: "StoreyBoardIdofYourViewController") as! UINavigationController

     self.window?.rootViewController = controller
}

这将启动D viewcontroller .....

答案 4 :(得分:1)

您可以在应用delegate.m文件中查看是否首次安装的应用ViewController A将显示为初始视图控制器,否则查看控制器D。请在以下功能中进行检查:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//check the initial view controller here//
        return true
    }

Swift 3:

let launchBefore = UserDefaults.standard.bool(forKey: "launchBefore")
if launchBefore  {
    print("Not first launch.") } else {
    print("First launch, setting UserDefault.")
    UserDefaults.standard.set(true, forKey: "launchBefore") }

答案 5 :(得分:0)

您正在使用一个导航控制器,因此很难实现您的行为。您可以更轻松地为视图A和D使用单独的视图控制器,并使用以下方法调用它们:

present(vc, animated: true)

并解雇致电:

dismiss(animated: true)