I am trying to understand delegation in Swift better, and I have seen how delegation can be used to pass data from a second view controller back to an initial view controller. But I am confused about how to pass data from the initial view to a second view using delegation. I have initialized an instance of the delegate in my initial view and implement the delegate protocol in the second view, but I am still unsuccessful in passing the data from initial view to second view using delegation. Any advice on what I might be doing wrong would be appreciated! Here is the storyboard view of what my delegation attempt looks like. 1
Initial View Class:
import UIKit
class ViewController: UIViewController {
var data: DataDelegate?
@IBOutlet weak var text: UITextField!
@IBOutlet weak var send: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func send(_ sender: Any) {
let msg = text.text!
data?.sendData(data: msg)
print("SENDING MESSAGE: \(msg)")
}
}
protocol DataDelegate {
func sendData(data: String)
}
Second View Class:
import UIKit
class RVC: UIViewController, DataDelegate {
@IBOutlet weak var delegationLabel: UILabel!
@IBOutlet weak var message: UILabel!
@IBOutlet weak var back: UIButton!
let vc = ViewController()
func sendData(data: String) {
print("DATA SENT")
let msg = data
print(msg)
message.text = data
}
override func viewDidLoad() {
super.viewDidLoad()
print("LOADED")
vc.data = self
// Do any additional setup after loading the view.
}
}