【问题标题】:label disappears when i launch app the second time当我第二次启动应用程序时标签消失
【发布时间】:2019-09-07 23:40:40
【问题描述】:

所以我有一个带有三个 Viewcontroller 的 main.storyboard。在第一个视图控制器中,有一个带有 perform.segue 方法的开始按钮到第二个视图控制器。在第二个视图控制器中,有一个文本字段询问用户的姓名。当用户输入他的名字并点击继续按钮时,textfield.text(人名)通过prepare(for segue)方法被放入第三个视图控制器的标签中。当我第一次启动我的应用程序时,就会发生此过程。当我第二次启动我的应用程序时,在没有第一个和第二个视图控制器的“欢迎程序”的情况下显示 thirsViewcontroller,但标签消失了。

第二个ViewController的代码


@IBAction func continueButton(_ sender: Any) {
        animateButton()

        if enterYourNameTextfield.text != "" {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.8, execute: {
            self.performSegue(withIdentifier: "thirdScreenSegue", sender: self)

            }
        )}
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let thirdController = segue.destination as! thirdViewController
        thirdController.myString = "Hello \(enterYourNameTextfield.text!)! How are you today ?"

    }

第三个Viewcontroller的代码


@IBOutlet weak var helloNameLabel: UILabel!
var myString = String()

AppDelegate.swift 文件的代码



  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool  {
    let isFirst = UserDefaults.standard.bool(forKey: "isLaunched") // edited this after rmaddy's comment
    var viewControllerWithIdentifier = "initialView"

        if !isFirst {
    UserDefaults.standard.set(true, forKey: "isLaunched")
    viewControllerWithIdentifier = "firstView"
    }
    let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let initialViewController : UIViewController = mainStoryboard.instantiateViewController(withIdentifier: viewControllerWithIdentifier) as UIViewController
    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = initialViewController
    self.window?.makeKeyAndVisible()
    sleep(2)

        return true
    }


【问题讨论】:

    标签: swift segue viewcontroller


    【解决方案1】:

    在 secondViewController 中,您需要保留用户的名称。您可以通过多种方式保留用户名,但对于您的用例,您可以将名称保存在用户默认值中,如下所示:

     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            let name = enterYourNameTextfield.text ?? ""
            UserDefaults.standard.set(name, forKey: "name")
        }
    

    在您的 thirdViewController 的 viewDidLoad 方法中,您可以检索用户名,如下所示

    override func viewDidLoad(){
       let name = UserDefaults.standard.string(forKey: "name") ?? ""
       myString = "Hello \(name)! How are you today ?"
    }
    

    【讨论】:

    • 所以应用程序崩溃,我输入名称并单击继续
    • 它给出了一个错误线程1:致命错误:在展开name = UserDefaults.standard.string(forKey: "name")后面的可选值时意外发现nil
    • 您需要先解开 userDefaults。让我知道它是否工作正常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多