4

My text right now saves the textfield in a uiviewcontroller but when a go to the previous view controller than back to the original view controller the text is erased. How can I save the text so that when the text is entered and saved the text stays their.

import UIKit class tryingViewController: UIViewController { @IBOutlet weak var textext: UITextField! @IBAction func actionaction(_ sender: Any) { textext.resignFirstResponder() let myText = textext.text UserDefaults.standard.set(myText, forKey: "myKey") } } 

2 Answers 2

4

There are several options you could use.

  1. Using CoreData
  2. Saving the text in your main view controller
  3. Storing it in UserDefaults

Seeing as you're already using UserDefaults, I'll just stick with it and show an example:

@IBOutlet weak var textField: UITextField! let standardText = "standardText" override func viewDidLoad() { super.viewDidLoad() textField.addTarget(self, action: #selector(textDidChange), for: .editingChanged) textField.text = UserDefaults.standard.value(forKey: standardText) as? String } func textDidChange(sender: UITextField) { UserDefaults.standard.set(sender.text ?? "", forKey: standardText) } 
Sign up to request clarification or add additional context in comments.

2 Comments

A cautionary note on using UserDefaults to store sensitive information. andyibanez.com/nsuserdefaults-not-for-sensitive-data
Good point in case OP wants to store sensitive data. I only created this example purely because OP was using it already and I have no idea what he wants to do with it :).
-1

You're setting the defaults but you're not reading back out of it:

if let string = UserDefaults.standard.object(forKey: "myKey") as? String { textext.text = string } 

Or as pointed out, since the textfields text is optional:

textext.text = UserDefaults.standard.object(forKey: "myKey") as? String 

2 Comments

You don't even need checking if there is a string in the defaults as default text value of text field is null. Just do textfield.text = UserDefaults.standard.object(forKey: "myKey") as? String
@ozgur In this case, you are correct since text is optional.