Reputation: 766
I'm trying to understand delegates so I created this simple app to test it out, I just want to pass a string from the secondViewController to the MainViewController... I tried to follow all the steps but it seems there's something missing and I don't have a clue about what it might possibly be... here's my code..
main view controller
class mainController: UIViewController, sendDataDelegate {
let label: UILabel = {
let lab = UILabel()
lab.text = "No data"
lab.textAlignment = .center
lab.translatesAutoresizingMaskIntoConstraints = false
return lab
}()
let tapRecognizer = UITapGestureRecognizer()
let secondVC = SecondViewController()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.green
// assign delegate to self, not working...
secondVC.delegate = self
tapRecognizer.addTarget(self, action: #selector(goToSecondVC))
view.addGestureRecognizer(tapRecognizer)
view.addSubview(label)
// label constraints..
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":label]))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-200-[v0]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":label]))
}
@objc func goToSecondVC(){
show(SecondViewController(), sender: nil)
}
func passData(str: String) {
print(str)
label.text = str
}
}
and the second view controller plus protocol to send the data...
import UIKit
//protocol to pass the data..
protocol sendDataDelegate {
func passData(str: String)
}
class SecondViewController: UIViewController {
let tapRecog = UITapGestureRecognizer()
let dataStr = "data passed"
var delegate: sendDataDelegate?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.red
tapRecog.addTarget(self, action: #selector(goBack))
view.addGestureRecognizer(tapRecog)
}
@objc func goBack(){
// trying to pass data here..
delegate?.passData(str: dataStr)
// dismiss view...
dismiss(animated: true, completion: nil)
}
}
I'd like to point out I'm trying to learn everything by code, so no storyboards being used here.. how can I do this just by code?
thank you all in advance for the answers! have a great day)
Upvotes: 0
Views: 92
Reputation: 682
This correction will solve your problem:
@objc func goToSecondVC(){
show(secondVC, sender: nil)
}
Protocols are better to be named with a capital letter:
protocol SendDataDelegate: AnyObject {
func passData(str: String)
}
And don't forget about weak delegate:
weak var delegate: SendDataDelegate?
Upvotes: 2
Reputation: 1392
change goToSecondVC()
method as below:
@objc func goToSecondVC(){
let vc = SecondViewController()
vc.delegate = self
show(vc, sender: nil)
}
Upvotes: -1
Reputation: 77641
In your function goToSecondVC
you are creating a brand new view controller and ignoring the property that you created.
Change it to use secondVC
instead of SecondViewController()
.
Upvotes: 3