在引发另一个问题后,我现在尝试在AppDelegate类中快速声明一个全局用户名变量。我的目标是让用户在启动屏幕上输入用户名,然后在其他视图的标签上弹出该用户名-简单地说就是通用用户名。
我在AppDelegate类中声明了用户名
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var userName = ""
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
在我的主控制器中,我有一个标签和一个用于设置名称的按钮功能
class ViewController: UIViewController {
@IBOutlet var userLabel : UILabel!
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func setName (){
appDelegate.userName = userLabel.text!;
}
}
当时的想法是,该名称将在我的player2控制器的标签中弹出
import Foundation
import UIKit
class Player2 : UIViewController {
@IBOutlet var player2 : UILabel!
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.player2.text = appDelegate.userName as? String
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
这是一种userName
从ViewController
另一种传递到另一种的简便方法ViewController
。
//Set your userName with specific key
@IBAction func setName (){
NSUserDefaults.standardUserDefaults().setObject(userLabel.text, forKey: "userName")
}
之后,您可以通过以下方式以SecondViewController
这种方式读取该值:
override func viewDidLoad() {
super.viewDidLoad()
let userName = NSUserDefaults.standardUserDefaults().objectForKey("userName") as! String
player2.text = "\(userName)"
}
您无需在AppDelegate
类中声明任何变量。
只需从userLabel.text
您的ViewController
课程中获取价值并进行存储即可。之后,您可以从NSUserDefaults
项目中的任何位置读取它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句