如何从导航控制器切换到选项卡控制器并使其成为根视图控制器

时间:2016-10-31 00:32:14

标签: ios iphone swift2

您好我在导航控制器中有登录屏幕和注册屏幕,用于用户登录或想要在应用程序中注册。我还创建了一个显示主页屏幕的Tab控制器。在用户登录或注册后,我希望能够切换到选项卡控制器并使其成为根视图控制器,因此用户无法返回登录或注册页面。请问如何实现这一目标?

用户登录时,下面是几行代码

if statusCode == 200 {
                do {
                    let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
                    let result = json as? [String: AnyObject]
                    guard let token = result!["token"], let firstname = result!["user"]!["firstname"]! else {
                        print("Error: \(error?.debugDescription)")
                        return
                    }

                    NSUserDefaults.standardUserDefaults().setObject(token, forKey: "token")
                //code to segue to the tab controller from the nav controller (login screen)
                self.getHome()

                }
                catch {
                    print("Error receiving data")
                }
            }
        })
        task.resume()



    func getHome() {
     let storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let tableController = storyboard.instantiateViewControllerWithIdentifier("tabController") as? UITableViewController

        let appledDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        appledDelegate.window?.rootViewController = tableController
 }

在我的文件中的AppDelegate.swift中检查是否有令牌,如果没有调用登录页面或显示主页:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    let obj = NSUserDefaults.standardUserDefaults().objectForKey("token")

    if obj == nil {

    let welcomeHomeController:UIViewController = WelcomeHomeController(nibName: nil, bundle: nil)
    welcomeHomeController.view.backgroundColor = UIColor.whiteColor()
    let navController:UINavigationController = UINavigationController(rootViewController: welcomeHomeController)

    //create window
    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
    self.window?.backgroundColor = UIColor.darkGrayColor()
    self.window?.rootViewController = navController
    self.window!.makeKeyAndVisible()

    return true

    }

1 个答案:

答案 0 :(得分:0)

func getHome() {
 let storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let navController = storyboard.instantiateViewControllerWithIdentifier("tabController") as? UINavigationController //be sure to set the "tabController" in the navigationController and not in the tabcontroller

    let next = navController.topViewController as! YourTabRootViewController
    self.navigationController.presentViewController(next, animated: true, completion: nil)

 }