Hello,
I'm a beginner with Swift and I'm struggling to understand the way the variables are send between page_1 and page_2 using delegate and protocols.
I have a 2-page application: ViewController1.swift and ViewController2.swift
- on page 1 (ViewController1.swift) I have a textbox (TextBoxControl) and a button.
- on page 2 (ViewController2.swift) I have a label and a button
I want to send text in thextbox from page_1 to page_2 and print it in page_2.
The problem is that the delegated is always nil (it prints on the console
... print ("Delegate is nil"). )
Technologies: XCODE Version 9.4.1, swift 4
How can I solve this?
Thanks in advance.
CODE - page1 ( ViewController1 ):
import UIKit
protocol delegate_transmisie_date_1_2{
func transmisie(text1: String)
}
class ViewController1: UIViewController {
var delegate: delegate_transmisie_date_1_2?
@IBOutlet weak var text1: UITextField!
@IBAction func btn_Send_Date_Using_DelegateAndProtocol(_ sender: Any) {
if self.delegate != nil {
self.delegate?.transmisie(text1: text1.text!)
}else{
print("Delegate is nil")
}
let selectionView = storyboard?.instantiateViewController(withIdentifier: "ID_PAGE2") as! ViewController2
present(selectionView, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
CODE - PAGE2 ( ViewController2 )
import UIKit
class ViewController2: UIViewController, delegate_transmisie_date_1_2 {
@IBOutlet weak var label1: UILabel!
func transmisie(text1: String, text2: String) {
label1.text = text1
}
@IBAction func btn_CloseWindow(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
//This is the place where the delegate must by set ?????
let pagina1 = storyboard?.instantiateViewController(withIdentifier: "ID_PAGINA1") as! ViewController1
pagina1.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}