I'm recently studying Swift. I create projects of varying complexity, but I still don't understand the essence of delegating. In my projects, I try to avoid it in every possible way. I watched various videos on this topic, read articles, but I could not understand the essence of delegation. Now I decided to devote some time to this and created a simple project to figure it out, but I still can't get it.
I want to pass text when clicking on a button from FirstViewController to SecondViewController , but this code doesn't work, what is the reason? What am I doing wrong?
protocol Protocol {
func fillTheLabel(with text: String)
}
class FirstViewController: UIViewController {
var delegate: Protocol?
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func buttonPressed(_ sender: Any) {
let text = "Some Text Here"
delegate?.fillTheLabel(with: text)
}
}
// there is a segway between the button and the SecondViewController
class SecondViewController: UIViewController, Protocol {
var firstVC: FirstViewController?
@IBOutlet var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
firstVC?.delegate = self
}
func fillTheLabel(with text: String) {
label.text = text
}
}