Swift:以编程方式导航到ViewController并传递数据

时间:2015-08-04 15:56:00

标签: ios swift uinavigationcontroller uistoryboardsegue

我最近开始学习swift,到目前为止一直很好。目前我在尝试在视图控制器之间传递数据时遇到问题。我设法弄清楚如何使用导航控制器以编程方式在两个视图控制器之间导航。现在唯一的问题是我很难弄清楚如何将用户输入的三个字符串(对于json api)传递给下一个视图。

这是我目前的尝试。非常感谢任何帮助!

的ViewController:

/* Get the status code of the connection attempt */
func connection(connection:NSURLConnection, didReceiveResponse response: NSURLResponse){

    let status = (response as! NSHTTPURLResponse).statusCode
    //println("status code is \(status)")

    if(status == 200){

        var next = self.storyboard?.instantiateViewControllerWithIdentifier("SecondViewController") as! SecondViewController
        self.presentViewController(next, animated: false, completion: nil)
    }
    else{

        RKDropdownAlert.title("Error", message:"Please enter valid credentials.", backgroundColor:UIColor.redColor(), textColor:UIColor.whiteColor(), time:3)
        drawErrorBorder(usernameField);
        usernameField.text = "";
        drawErrorBorder(passwordField);
        passwordField.text = "";
    }
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {

    let navigationController = segue.destinationViewController as! UINavigationController
    let newProjectVC = navigationController.topViewController as! SecondViewController
    newProjectVC.ip = ipAddressField.text
    newProjectVC.username = usernameField.text
    newProjectVC.password = passwordField.text
}

SecondViewController:

import UIKit

class SecondViewController: UIViewController {

var ip:NSString!
var username:NSString!
var password:NSString!

override func viewDidLoad() {
    super.viewDidLoad()

    println("\(ip):\(username):\(password)")
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

2 个答案:

答案 0 :(得分:4)

当您的应用程序的故事板执行segue(您使用Interface Builder在故事板中创建的连接)时,将调用方法false。在上面的代码中,您使用prepareForSegue自己呈现控制器。在这种情况下,presentViewController不会被触发。您可以在呈现控制器之前立即进行设置:

prepareForSegue

您可以阅读有关segue here

的更多信息

答案 1 :(得分:2)

更新了Swift 3的语法:

    let next = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController 
    next.ip = ipAddressField.text
    next.username = usernameField.text
    next.password = passwordField.text
    self.present(next, animated: true, completion: nil)