检查是否已将委派设置为正确的vc,以及是否实现了必需的委托方法。如果还是不行,可以尝试使用类似下面的代码示例:
在ViewController中添加协议:
protocol MyDelegate: AnyObject {
func didTapButton()
}
class ViewController: UIViewController {
weak var delegate: MyDelegate?
@IBAction func buttonTapped(_ sender: UIButton) {
delegate?.didTapButton()
}
// ...
}
在推送ViewController的另一个类中,设置自己为Delegate:
class OtherViewController: UIViewController, MyDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = mainStoryboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
vc.delegate = self
navigationController?.pushViewController(vc, animated: true)
}
func didTapButton() {
print("Button tapped")
}
// ...
}