[英]Swift change method in ViewDidLoad
我正在尝试使用以下代码更改ViewDidLoad中的方法:
在课堂宣告中:
var nextValue: Int!
在ViewDidLoad中:
if nextValue == nil {
print("Hi")
} else if nextValue == 2 {
print("Hello")
}
最后,该函数更改nextValue的值:
func buttonAction(sender: AnyObject) {
self.performSegueWithIdentifier("nextView", sender: self)
nextValue = 2
}
当我从“ nextView”移回第一个视图时,nextValue应该为2,但为零。 我究竟做错了什么?
您对视图生命周期的理解是错误的。
首先,在类声明中使用nil值声明变量。 然后,在viewDidLoad方法中检查其值,最后通过一些按钮操作更改其值。
但是,当您通过segue转到nextView离开视图控制器屏幕时,firstView将被释放,并且当您再次表示它时,循环回到声明级别。 由于您将变量值声明为nil,因此它将始终显示nil值。
如果要保留其值,则需要将其保存在其他位置,NSUserDefault似乎是存储其值的不错选择。
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
nextValue = NSUserDefaults.standardUserDefaults().valueForKey("nextValue") as? Int
if nextValue == nil {
print("Hi")
} else if nextValue == 2 {
print("Hello")
}
}
func buttonAction(sender: AnyObject) {
self.performSegueWithIdentifier("nextView", sender: self)
nextValue = 2
NSUserDefaults.standardUserDefaults().setInteger(2, forKey: "nextValue")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.