获得2个ViewControllers第一个是ViewController 2nd TableViewCotnroller
class ViewController: UIViewController, CLLocationManagerDelegate, TabVCDelegate {
func reciveData(_ numberOfRows: Int) {
print(numberOfRows)
}
...
}
TableViewController:
protocol TabVCDelegate {
func reciveData(_ numberOfRows: Int)
}
class TabVC: UITableViewController {
var delegate: TabVCDelegate?
@IBAction func passDataBack(_ sender: UIButton) {
delegate?.reciveData(5)
self.dismiss(animated: true, completion: nil)
print(delegate ?? "show me if its nil")
}
我的委托人?.reciveData(5)由于某种原因无法解决问题 当我有2个正常的ViewController时,它确实起作用了,我是否缺少有关TableViewControllers的东西?还是其他的东西? 任何帮助将不胜感激。
答案 0 :(得分:1)
第一项:
使该delegate
属性weak
避免强烈的引用周期
weak var delegate: TabVCDelegate?
要实现您的协议应符合class
protocol TabVCDelegate: class {
func reciveData(_ numberOfRows: Int)
}
下一个:
您必须将该委托设置在某个地方。如果您在TabVC
类中引用了ViewController
实例,则它看起来像这样:
tabVC.delegate = self
HERE是有关“如何在Swift中创建委托”的详细说明
答案 1 :(得分:0)
谢谢
实际上我确实找到了缺失的东西,在segue中我忘记了在设置segue时将destinationVC.delegate设置为self :
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToTableView"{
let destinationVC = segue.destination as! TabVC
destinationVC.delegate = self // <-- this line was missing
destinationVC.dataPassedThroughSegue = locationLabel.text
}
}