仅在首次启动时显示视图 - Swift 3

Show a View on First Launch Only - Swift 3

我正在我的应用程序中实施条款和条件视图,用户必须接受它们才能继续,然后当他们接受它们时,他们不再需要通过条款和条件视图。我遵循了有关如何集成 UserDefaults 并在有人接受条款的情况下在本地存储值的教程。但是我坚持将它实现到根视图控制器中。特别停留在我的 viewDidAppear 函数上。 if 和 else 语句中的内容是什么?

class TermsAndConditionsViewController: UIViewController, UITextViewDelegate {

@IBOutlet weak var termsTextView: UITextView! {
    didSet {
        termsTextView.delegate = self
    }
}

@IBOutlet weak var acceptButton: UIButton! {
    didSet {
        acceptButton.isHidden = true
    }
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    acceptButton.isHidden = scrollView.contentOffset.y + scrollView.bounds.height < scrollView.contentSize.height
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    if UserDefaults.standard.bool(forKey: "termsAccepted") {

    } else {

    }
}

@IBAction func acceptButtonTapped(_ sender: Any) {
    performSegue(withIdentifier: "toPeekView", sender: sender)
}

}

可能,你的意思是 "Show a ViewController on First Launch Only"。

为此目的使用 UserDefaults 是个好主意,但是,检查接受的术语是否应该 而不是 TermsAndConditionsViewController 层,相反,它应该在AppDelegate - application:didFinishLaunchingWithOptions,你可以在其中决定根 ViewController 应该是 TermsAndConditionsViewController 还是另一个 ViewController(例如 HomeViewController)。

AppDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    let rootViewController = storyboard.instantiateViewController(withIdentifier: UserDefaults.standard.bool(forKey: "termsAccepted") ? "termsViewControllerID" : "homeViewControllerID")

    window?.rootViewController = rootViewController

    return true
}

条款和条件ViewController:

class TermsAndConditionsViewController: UIViewController {
    //...

    @IBAction func acceptButtonTapped(_ sender: Any) {
        UserDefaults.standard.set(true, forKey: "termsAccepted")

        performSegue(withIdentifier: "toPeekView", sender: sender)
    }

    //...
}

希望对您有所帮助。