继我发布的另一个问题之后,我现在尝试在 AppDelegate 类中快速声明一个全局用户名变量。我的目标是让用户在启动屏幕中输入他的用户名,然后让该用户名在其他 View 的标签上弹出 - 一个简单的通用用户名。
我已经在我的 AppDelegate 类中声明了用户名
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var userName = ""
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
在我的主 Controller 中,我有一个标签和一个设置名称的按钮功能
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 Controller 的标签中弹出
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
类中声明任何变量。
只需从 ViewController
类中的 userLabel.text
获取值并存储它。之后,您可以在项目的任何位置从 NSUserDefaults
读取它。
关于ios - 在 AppDelegate Swift 中传递全局用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31827221/