我正在开发一个演练屏幕,该屏幕应该仅在用户首次打开应用时出现。到目前为止,我创建了演练页面和PageViewController。
看图:
我在这里阅读了很多类似的问题,我明白我必须使用
UserDefaults()
在AppDelegate中,但我不明白如何在代码中使用类和故事板名称。 基本上,当第一次打开应用程序时,PageViewController应出现在屏幕上,当用户点击WalkThroughScreen上的开始按钮时,它将关闭教程页面,应用程序将启动。
我试过这段代码:
if let isFirstStart = UserDefaults.standard.value(forKey: "isFirstLaunch") as? Bool {
if defaults.bool(forKey: "isFirstLaunch") {
defaults.set(false, forKey: "isFirstLaunch")
let mainStoryboard = UIStoryboard(name: "WalkThroughScreen", bundle: Bundle.main)
let vc : WalkThroughScreen = mainStoryboard.instantiateViewController(withIdentifier: "PageViewController") as! WalkThroughScreen
self.present(vc, animated: true, completion: nil)
}
我很确定这是一个完整的混乱,因为我不太了解它并且我没有使用TutorialPage,所以如果有人留下我的提示或示例如何正确地执行它,我将非常感激
答案 0 :(得分:3)
是的,你是对的,你必须使用userDefaults
来实现这一目标。你必须在appDelegate()
内完成
Roel Koops答案应该这样做,但你也可以这样尝试:
let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore")
if launchedBefore {
print("This is not first launch.")
} else {
print("This is first launch.")
UserDefaults.standard.set(true, forKey: "launchedBefore")
UserDefaults.standard.synchronize()
let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let vc : WalkThroughScreen = mainStoryboard.instantiateViewController(withIdentifier: "WalkThroughScreen") as! WalkThroughScreen
self.present(vc, animated: true, completion: nil)
}
并确保声明:let userDefaults = UserDefaults.standard
并在didFinishLaunchingWithOptions
内使用。
还有更多解决方案,所以我再给你一个:
let userDefaults = UserDefaults.standard
if !userDefaults.bool(forKey: "launchedBefore") {
let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let vc : WelcomeViewController = mainStoryboard.instantiateViewController(withIdentifier: "WalkThroughScreen") as! WelcomeViewController
self.window?.makeKeyAndVisible()
self.window?.rootViewController?.present(vc, animated: false, completion: nil)
userDefaults.set(true, forKey: "launchedBefore")
userDefaults.synchronize()
}
您甚至可以在一行中声明所有故事板内容:
self.window?.rootViewController = self.storyboard?.instantiateViewController(withIdentifier: "WalkThroughScreen")
但这假设您声明了2个变量:
var window: UIWindow?
var storyboard: UIStoryboard?
如果它不起作用,请告诉我,我会尽力帮助。
答案 1 :(得分:2)
如果密钥“isFirstLaunch”不存在,则永远不会执行if-block中的代码。
试试这个:
if let isFirstStart = UserDefaults.standard.value(forKey: "isFirstLaunch") as? Bool {
print("this is not the first launch")
} else {
print("this is the first launch")
UserDefaults.standard.set(false, forKey: "isFirstLaunch")
UserDefaults.standard.synchronize()
let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let vc : WalkThroughScreen = mainStoryboard.instantiateViewController(withIdentifier: "WalkThroughScreen") as! WalkThroughScreen
self.present(vc, animated: true, completion: nil)
}