gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:07:44 24 4
gpt4 key购买 nike

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

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

View Controller :

/* 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
}

第二 View Controller :

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.
}
}

最佳答案

prepareForSegue 方法在您的应用程序的 Storyboard 执行转场(您在 Storyboard 中使用 Interface Builder 创建的连接)时调用。在上面的代码中,尽管您自己使用 presentViewController 呈现 Controller 。在这种情况下,不会触发 prepareForSegue。您可以在展示 Controller 之前进行设置:

let next = self.storyboard?.instantiateViewControllerWithIdentifier("SecondViewController") as! SecondViewController
next.ip = ipAddressField.text
next.username = usernameField.text
next.password = passwordField.text
self.presentViewController(next, animated: false, completion: nil)

您可以阅读有关 segue 的更多信息 here

关于ios - Swift:以编程方式导航到 ViewController 并传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31813942/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com