I'm developing a build your own adventure app with 2 buttons that change their .setTitle every time they are being pressed. My app is ready- everything works as it should. Whenever a button is pressed, the the story textview changes, and my buttons present new titles. The only thing I have left is finding a way to save the most recent titles my buttons presented
for when users return to the app after closing it.
Using UserDefaults.Standard has helped me save the story textview, but so far I couldn't find a way to save the changing titles (.setTitle) for my buttons.
This is how I managed to save the textview:
let defaults = UserDefaults.standard
func savePageTopText() {
defaults.set(storyTextView.text, forKey: "topText")
}
func checkTopPageText() {
let pageText = defaults.value(forKey: "topText") as? String
storyTextView.text = pageText
}
I then added the savePageTopText() to each of my buttons, and the checkTopPageText() to viewDidLoad.This is how the titles for my buttons are coded, and they change whenever a button is pressed:
let answer1a = "Turn left"
let answer1b = "Turn right"
let answer2a = "Keep driving!"
let answer2b = "Pull over!"
@IBAction func buttonPressed(_ sender: UIButton) {
if sender.tag == 1 && storyIndex == 1 {
storyTextView.text = story3
topButton.setTitle(answer3a, for: .normal)
bottomButton.setTitle(answer3b, for: .normal)
savePageTopText()
}
}
I hope I'm being clear enough about everything- doing my best. When users close the app, how can I make sure they return to the same and most recent titles the buttons presented? How do I SAVE the buttons setTitle with user default?
You are doing all the things correctly like saving but while fetching you are doing the mistake.
UserDefaultshas the type to fetch the data likeString,Int,Array, etc.So here is how you can fetch the saved
String.Just like you need to know that what data is being saved and then only you can fetch using appropriate methods.