Hi guys hope you are doing good. I have a doubt in when I try to use custom delegate function the call back function is not being called without using prepare segue or present view controller is it possible to achecive this without these two concepts are used to only for handle front and back controllers directly . Simply I say I have 3 viewControllers and I want to update my firstviewcontroller label when I did something in 3rd view controller. Is it possible via delegate? Please help me out I am struggling for last two days I could not find an answer so please guide me.
Here is my code In my 3rd view controller
protocol ThirdViewControllerDelegate: class {
func updateLabel(title: String)
}
Then I have created a property weak var delegate: ThirdViewControllerDelegate?
And I have assigned a value in
@IBAction func thirdControllerButtonTapped(_ sender: UIButton) {
delegate?.updateLabel(title: "iOS_Developer")
dismiss(animated: true, completion: nil)
}
And I have adopted this delegate in my first view controller and
lazy var thirdController = ThirdViewController()
thirdController.delegate = self
func updateLabel(title: String) {
print("Your updated Label is \(title)")
}
But this function not being called . Here how can I set delegate reference so please help me.
答案 0 :(得分:0)
override func prepare(for segue: UIStoryboardSegue,
sender: Any?) {
if let vc = segue.destination as? ThirdViewController {
vc.delegate = self
}
}
or:
let vc = ThirdViewController()
vc.delegate = self
self.navigationController?.pushViewController(vc, animated: true)
See https://developer.apple.com/documentation/uikit/uinavigationcontroller/1621887-pushviewcontroller
Here's a diagram which hopefully shows how the view controllers communicate with each other via delegates: