我正在创建一个简单的事实应用程序(在swift中)并且所有事实都在单独的视图控制器中,当用户关闭应用程序时,它们都进入主页面,您必须再次从事实1开始。
我想知道如何保存用户关闭时所使用的视图控制器,以及当他们再次继续查看事实时,它会从这个事实开始。谢谢:)如果有人制作视频,我认为它将获得足够的视图来启动YT频道
答案 0 :(得分:2)
您可以使用NSUserDefaults
来记住上次ViewController
。
首先,当你加载如下所示的任何视图时,你必须存储一些整数:
<强> FirstView.swift 强>
override func viewDidLoad() {
super.viewDidLoad()
NSUserDefaults.standardUserDefaults().setInteger(0, forKey: "View")
// Do any additional setup after loading the view, typically from a nib.
}
<强> SecondViewController.swift 强>
override func viewDidLoad() {
super.viewDidLoad()
NSUserDefaults.standardUserDefaults().setInteger(1, forKey: "View")
// Do any additional setup after loading the view.
}
现在在 AppDelegate.swift 中读取存储的值并以这种方式加载与该Integer相关的ViewController:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let viewCount = NSUserDefaults.standardUserDefaults().integerForKey("View")
var VC = UIViewController()
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
println(viewCount)
if viewCount == 0 {
//FirstView should initiate
VC = storyboard.instantiateViewControllerWithIdentifier("First") as! ViewController
} else if viewCount == 1 {
//SecondView should inititate
VC = storyboard.instantiateViewControllerWithIdentifier("Second") as! SecondViewController
} else {
//ThirdView Should Initiate
VC = storyboard.instantiateViewControllerWithIdentifier("Third") as! ThirdViewController
}
self.window?.makeKeyAndVisible()
self.window?.rootViewController = VC
return true
}
查看THIS示例项目以获取更多信息。