以编程方式从Swift中的一个UIViewController移动到另一个UIViewController

时间:2014-09-04 11:28:53

标签: ios swift

我有2个ViewControllers。我没有故事板。一旦在第一个viewController中完成所有操作,我想从第一个视图移动到另一个视图。这样做的方法是什么?它是这样的,第一个视图显示图像,在后台显示一些API调用。 API调用成功后,我希望它移动到第二个ViewController(LoginActivityViewController)。我尝试在第一个ViewController中调用它:

var loginActivity = LoginActivityViewController()
self.navigationController.pushViewController(loginActivity, animated: true)

但是,这不起作用。怎么做?

这是我在AppDelegate中的应用程序功能

func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
    // Override point for customization after application launch.
    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    let navigationController: UINavigationController = UINavigationController(rootViewController: RootViewController())
    navigationController.setNavigationBarHidden(true, animated: false)
    window!.rootViewController = navigationController
    window!.makeKeyAndVisible()
    return true
}

这是我的RootViewController的viewDidLoad()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    let image1 = UIImage(named: "Default.png")
    let imageview = UIImageView(image: image1)
    self.view.addSubview(imageview)
    var loginActivity = LoginActivityViewController()
    self.navigationController.pushViewController(loginActivity, animated: true)
}

2 个答案:

答案 0 :(得分:2)

这个方法应该如何正确启动导航控制器:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {

    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    let rootViewController: RootViewController = RootViewController(nibName: "RootViewController", bundle: nil)
    let navigationController: UINavigationController = UINavigationController(rootViewController: rootViewController)
    window!.rootViewController = navigationController
    window!.makeKeyAndVisible()
    return true
}

现在您可以将新的视图控制器推送到层次结构中。


更新

如果您不想显示导航栏,请将此行插入上面的代码中。

navigationController.setNavigationBarHidden(true, animated: false)

答案 1 :(得分:0)

var next = self.storyboard?.instantiateViewControllerWithIdentifier("DashboardController") as! DashboardController
self.presentViewController(next, animated: true, completion: nil)

不要忘记在StoryBoard Id - >中设置ViewController StoryBoard identity inspector