I am pretty new to programming with Xcode/Swift and I am facing a small problem.
I want to send information from a ViewController to a second ViewController using delegate and without segue. I read a lot about that and found the most common solution is using the "instance".delegate = self in ViewDidLoad but it just does not work for me.
-- Definition of App --
It's pretty easy. On the first ViewController I have a button and a Label. The button opens the second ViewController, which has a textField and a Button. The Button sends what is in the textField to the first ViewController to update the Label.
-- Code --
This is the code for the first ViewController:
class ViewController: UIViewController, clickedButtonDelegate {
@IBOutlet weak var Label: UILabel!
func didClickedButton(text: String) {
Label.text = text
}
var secondView = SecondViewController()
override func viewDidLoad() {
super.viewDidLoad()
secondView.delegate = self
}
}
This is the code for the second ViewController:
protocol clickedButtonDelegate {
func didClickedButton(text: String)
}
class SecondViewController: UIViewController {
@IBOutlet weak var introducedText: UITextField!
var delegate : clickedButtonDelegate!
@IBAction func sendData(_ sender: Any) {
if delegate != nil {
let information:String = introducedText.text!
delegate!.didClickedButton(text: information)
dismiss(animated: true, completion: nil)
self.navigationController?.popViewController(animated: true)
}
}
}
Using this code nothing happens because the delegate is always nil in SecondViewController.
Could you please help?
Thank you in advance!