I know, the topic of this question was asked several times before but I don't get the right solution for my problem, so I hope someone can help me.
I have two viewControllers
. In firstVC
, I change my text with an textView
. This text is stored in UserDefaults
. So now, I'd like to display the stored text on my secondVC
in a textView
.
My code for firstVC
:
class editprofileViewController: UIViewController {
@IBOutlet weak var changeTextInput: UITextField!
let defaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
let stringKey = UserDefaults.standard
changeTextInput.text = stringKey.string(forKey: "savedStringKey")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func change(_ sender: Any) {
let myText = changeTextInput.text;
UserDefaults.standard.set(myText, forKey: "savedStringKey")
UserDefaults.standard.synchronize()
}
}
Here I write the text in the textfield and store it.
My secondVC
:
self.bioTxt.text = // here should be the text from firstVC
bioTxt.isUserInteractionEnabled = false
bioTxt.textAlignment = NSTextAlignment.center
Thanks for your help!
First ViewController
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var txtView: UITextView! //your textView
override func viewDidLoad() {
super.viewDidLoad()
}
//MARK: - Button Action
@IBAction func btnClick(_ sender: UIButton) {
let userDefaultStore = UserDefaults.standard //userDefault object
userDefaultStore.set(txtView.text, forKey: "key_Value") //store textView value in userDefault
//navigate secondViewController
let secondVC = storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
self.navigationController?.pushViewController(secondVC, animated: true)
}
}
Second ViewController
import UIKit
class SecondViewController: UIViewController {
@IBOutlet weak var txtView: UITextView! // your textView
override func viewDidLoad() {
super.viewDidLoad()
let userDefault = UserDefaults.standard //create UserDefault object
txtView.text = userDefault.string(forKey: "key_Value")!//get userdefault value using same key which used to store date and set in textView
txtView.isUserInteractionEnabled = false
}
}