问题
I am implementing a Terms & Conditions view into my app and the user has to accept them to proceed, then when they do accept them, they no longer have to go through the Terms & Conditions view. I followed a tutorial on how to integrate UserDefaults
and store the value locally if someone does accept the terms. However I am stuck with implementing it into the root view controller. Specifically stuck on my viewDidAppear
function. What goes in the if and else statements?
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)
}
}
回答1:
Probably, you mean "Show a ViewController on First Launch Only".
Using UserDefaults for this purpose is a good idea, however, checking if the term accepted should not be at the TermsAndConditionsViewController
layer, instead, it should be in AppDelegate - application:didFinishLaunchingWithOptions
, you can decide in it whether the root ViewController should be the TermsAndConditionsViewController
or the other ViewController (HomeViewController for example).
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
}
TermsAndConditionsViewController:
class TermsAndConditionsViewController: UIViewController {
//...
@IBAction func acceptButtonTapped(_ sender: Any) {
UserDefaults.standard.set(true, forKey: "termsAccepted")
performSegue(withIdentifier: "toPeekView", sender: sender)
}
//...
}
Hope this helped.
来源:https://stackoverflow.com/questions/41811070/show-a-view-on-first-launch-only-swift-3