I am very very new to coding and I am trying to make a simple app. The app is kind of questionnaire, it is going to ask you a questions and you have to put the answer in textField. The problem is when you try to go back to the previous page the text you've put in textField disappears. I want the text to stay there if you decide to change your answer some question.
This is the first view:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func startedButtonPressed(_ sender: UIButton) {
self.performSegue(withIdentifier: "goToPageTwo", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "goToPageTwo" {
let destinationVC = segue.destination as! PageTwoViewController
and this is the second page view:
import UIKit
class PageTwoViewController: UIViewController {
var textBox: String?
@IBOutlet weak var textFieldOne: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func backButtonPressed(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
What you can do is, you can use a callBack closure for this :
define a CallBack variable of type ((String) -> Void) in PageTwoViewController
In prepare(for:, sender) assign a closure to callBack variable of PageViewController instance.
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } var firstAnswer: String? // NEW_LINE_ADDED @IBAction func startedButtonPressed(_ sender: UIButton) {
self.performSegue(withIdentifier: "goToPageTwo", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToPageTwo" {
let destinationVC = segue.destination as! PageTwoViewController
destinationVC.textBox = firstAnswer //NEW_LINE_ADDED
destinationVC.callBack = { answer in //NEW_LINE_ADDED
self.firstAnswer = answer //NEW_LINE_ADDED
}
}
}
}
In PageTwoViewController do this
class PageTwoViewController: UIViewController {
var textBox: String?
var callBack: ((String)-> Void) //NEW_LINE_ADDED
@IBOutlet weak var textFieldOne: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
textfieldOne.text = textBox ?? "" //NEW_LINE_ADDED
}
@IBAction func backButtonPressed(_ sender: UIButton) {
callBack?(textfieldOne.text ?? "") //NEW_LINE_ADDED
self.dismiss(animated: true, completion: nil)
}