我试图了解委托人,所以我创建了一个简单的应用程序来对其进行测试,我只想将一个字符串从secondViewController传递给MainViewController ...我试图按照所有步骤进行操作,但似乎缺少一些东西我不知道它可能是什么...这是我的代码。
主视图控制器
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
}
}
和第二个视图控制器以及发送数据的协议...
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)
}
}
我想指出的是,我正在尝试通过代码学习所有内容,因此这里没有使用情节提要。如何仅通过代码来做到这一点?
提前谢谢大家的回答!祝你有美好的一天
答案 0 :(得分:3)
在函数goToSecondVC
中,您将创建一个全新的视图控制器,并忽略您创建的属性。
将其更改为使用secondVC
代替SecondViewController()
。
答案 1 :(得分:2)
此更正将解决您的问题:
@objc func goToSecondVC(){
show(secondVC, sender: nil)
}
协议最好用大写字母命名:
protocol SendDataDelegate: AnyObject {
func passData(str: String)
}
别忘了委派的弱者:
weak var delegate: SendDataDelegate?
答案 2 :(得分:-1)
更改goToSecondVC()
方法如下:
@objc func goToSecondVC(){
let vc = SecondViewController()
vc.delegate = self
show(vc, sender: nil)
}