我想打开另一个视图控制器,检查它是否是应用程序的第一次运行。它在我按下按钮时起作用,但当我调用方法openMap时就不行了。
class TutorialController: UIViewController {
override func viewDidLoad() {
//check if the app opens for the first time
if(UserDefaults.standard.bool(forKey: "HasLaunchedOnce"))
{
// app already launched
print("not first launch")
openMap()
}
else
{
// This is the first launch ever
UserDefaults.standard.set(true, forKey: "HasLaunchedOnce")
UserDefaults.standard.synchronize()
print("first launch")
openTutorial()
}
}
func openTutorial(){
}
@IBAction func openMap(){
print("openmap opened")
performSegue(withIdentifier: "openMap", sender: nil)
}
}发布于 2016-11-02 14:22:18
如果您已经将按钮连接到@IBAction func openMap(),则不应该在viewDidLoad中调用openMap()操作,而应该在viewDidAppear中使用相同的代码performSegue(withIdentifier: "openMap", sender: nil)
if(UserDefaults.standard.bool(forKey: "HasLaunchedOnce"))
{
// app already launched
print("not first launch")
performSegue(withIdentifier: "openMap", sender: nil)
}
...如果它不起作用,您可能在创建segue时犯了错误,并将Button直接连接到故事板中的目标ViewController,而不是连接两个控制器:

如果是这样,只需删除旧的segue,并按照上面图像上的方式重新创建它,并分配相同的segue id "openMap“。
编辑:请将您的segue的执行移到viewDidAppear而不是viewDidLoad,因为viewDidLoad是在创建ViewController对象时调用的,并且它还没有附加到窗口。
发布于 2016-11-02 14:20:39
好的,据我所知,您想要在openMap时执行一个segue“HasLaunchedOnce”。那么,您做错的是您正在调用@IBAction func。这是我的建议
如果你还想要那个按钮
例:
//if else statement
if(UserDefaults.standard.bool(forKey: "HasLaunchedOnce"))
{
// app already launched
print("not first launch")
anotherFunction()
}
//@ibaction (scrap this if you don't want the button)
@IBAction func openMap()
{
print("openmap opened")
anotherFunction()
}
//another function
func anotherFunction()
{
performSegue(withIdentifier: "openMap", sender: nil)
}希望这能帮上忙
https://stackoverflow.com/questions/40381620
复制相似问题