0

I have been trying a challenge out alone in Swift to do programmatically - with no use of storyboards.

My first view controller has a label and a button to go to the second view controller.

I created a navigation controller within the app delegate file, and then push to the second view controller when the button is pressed.

The second view controller has a textfield, a button to save the text, and a button to go back to the first view controller.

The UI is fine, but I cannot figure out how to save the text that is entered into the textfield which is on the second view controller, and then display this text in the label in the first view controller.

Can someone give me a clue as to how to do this?

Currently in my button going back to the first view controller I have this:

func handleBackToVC1() {

        self.navigationController?.popViewController(animated: true)
    }

Is this where I pass the data that is in the textfield and display it in the label? Also, should I give the label some text to start off with? But which would then get changed to what was entered into the textfield?

timman
  • 479
  • 5
  • 14

1 Answers1

1

use protocol delegate for passing data from SecondViewController to FirstViewController

protocol TextFieldDataDelegate: class {
    func saveText(_ text: String)
}

class SecondViewController: UIViewController {
   weak var delegate: TextFieldDataDelegate?

  //on save button tap call the delegate method
  delegate?.saveText(textField.text)
}

//set FirstViewController as delegate for TextFieldDataDelegate protocol

class FirstViewController: UIController, TextFieldDataDelegate {

 // when you create instance of SecondViewController assign the delegate as self
 let secondVC = SecondViewController()
 secondVC.delegate = self

  //in saveText set label text as passed from SecondVC
  func saveText(_ text: String) {
    self.textLabel.text = text
  }
}

Note: There are many similar questions like this, always search before asking the question. Thanks

Suhit Patil
  • 11,748
  • 3
  • 50
  • 60