gpt4 book ai didi

ios - 传递的 Segue 变量在加载后保持清除

转载 作者:行者123 更新时间:2023-11-28 10:20:34 25 4
gpt4 key购买 nike

所以我一直致力于学习 swift,我遇到了让我卡住了一段时间的问题。我使用序列将数据从第一个 Controller 传递到第二个 Controller 。

当我打印变量 onLoad 时,它会打印出传递的正确值,但是在我执行另一个函数(单击红色按钮)后,它不会打印出传递的值,而是打印出空白值。

var Level = 0;
var userId: String = "";
var clanId: String = "";
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print(userId); //prints 97
print(clanId); //prins 2
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func redButtonClick(sender: AnyObject) {
print(userId); //prints ""
print(clanId); //prins ""
}

正如您在代码中看到的那样,它似乎非常简单,但显然我不知道它是如何工作的,因为在加载之后变量中没有任何内容。

感谢大家的帮助!

----------------编辑--------------------

更改值 userId: String = "test"更改了值 clanId: String = "test"

它现在在 onload 函数中打印出来

 print(userId)
print(clanId)

results:
97
2
test
test

----------------添加------------

@IBAction func loginButton(sender: AnyObject) {
self.performSegueWithIdentifier("dashboard", sender: self);
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "dashboard")
{
let dutydash:dashboardController = segue.destinationViewController as! dashboardController;
dutydash.userId = self.userId;
dutydash.clanId = self.clanId;
}
}

最佳答案

下面是一个工作示例,确保您的数据已在 prepareForSegue 中设置。

class prevClass: UIViewController{

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "nextView" {
let destinationVC = segue.destinationViewController as! NextView
destinationVC.userId = "77789";
destinationVC.clanId = "Awesome Clan"

}
}
@IBAction func next(sender: AnyObject) {
self.performSegueWithIdentifier("nextView", sender: self)

}
}

class NextView: UIViewController {

var userId: String!
var clanId: String!

override func viewDidLoad() {
}

@IBAction func redButtonClick(sender: AnyObject) {
print(userId);
print(clanId);
}
}

关于ios - 传递的 Segue 变量在加载后保持清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35674879/

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