我正在尝试获取子视图控制器,它显示在主视图控制器底部的视图容器中。当我按下孩子中的按钮时,“从基本VC按下的按钮”打印到控制台,但是“从主VC按下的热按钮”没有。我需要打印要在主View Controller中调用的第二条消息的函数。这是相关的BasicViewController代码:
protocol BasicVCDelegate: class {
func warmButton()
}
class BasicViewController: UIViewController {
weak var BasicVCDelegate: BasicVCDelegate?
@IBOutlet weak var warmButton: UIButton!
@IBAction func warmButton(sender: AnyObject) {
print("Button pressed from Basic VC")
BasicVCDelegate?.warmButton()
}
}
来自ViewController.swift
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, BasicVCDelegate {
override func viewDidLoad() {
pauseButton.isEnabled = false
hideAll();
self.basicContainer.isUserInteractionEnabled = true;
self.basicContainer.isHidden = false;
self.timerLabel.text = String("00:00:00");
eventTable.dataSource = self
eventTable.delegate = self
loadEvents(event: "timer start")
super.viewDidLoad()
}
// CREATE SEGUEs
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let nav = segue.destination as? UINavigationController, let classBasicVC = nav.topViewController as? BasicViewController {
classBasicVC.BasicVCDelegate = self
}
}
// FUNCTIONS FOR BASIC VIEW CONTROLLER TO REFERENCE
func warmButton() {
print("Warm button pressed from main VC")
}
}
编辑: 从下面的每个人看来,ViewController中的以下代码部分似乎导致了问题(永远不会调用if语句中的行):
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let nav = segue.destination as? UINavigationController, let classBasicVC = nav.topViewController as? BasicViewController {
classBasicVC.basicVCDelegate = self
}
}
这可能是由于我对代表和prepareforsegue功能的不熟悉。需要帮助找出应该遵循的“if let”
编辑2: 根据某些用户的建议(仍未达到打印声明),将以上代码替换为以下代码:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let nav = segue.destination as? BasicViewController, let classBasicVC = nav.basicVCDelegate {
print("got here!!")
}
}
最终编辑: 谢谢您的帮助!在一些游戏之后,以下工作(除了在我解决它时改变为错误的警告 - 我可以忍受警告)。
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let nav = segue.destination as? BasicViewController, let classBasicVC = nav as? BasicViewController? {
classBasicVC?.basicVCDelegate = self
}
}
答案 0 :(得分:0)
应该是这而不是您上次编辑的代码:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let classBasicVC = segue.destination as? BasicViewController {
classBasicVC.basicVCDelegate = self
}
}
答案 1 :(得分:0)
您尚未将按钮的委托分配给ViewController
将此添加到ViewController的viewDidLoad
override func viewDidLoad() {
//other code
yourButton.BasicVCDelegate = self
}
对于委托变量使用驼峰案例也是一种很好的做法,例如basicVCDDelegate