How to save the uitext field so that the text remains from the view controller to view the controller

My text now saves the text field in the uiviewcontroller, but when I go to the previous view controller, and not to the original view controller, the text is erased. How to save text so that when you enter text and save its text remains.

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")
    }
}
+4
source share
2 answers

There are several options you could use.

  • Using CoreData li>
  • Saving text in the main view controller.
  • Save to UserDefaults

After seeing what you are already using UserDefaults, I just stick to 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)
}
+3

, :

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

, , :

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

Source: https://habr.com/ru/post/1663175/


All Articles