【发布时间】:2020-06-01 12:09:34
【问题描述】:
我有一个父视图控制器,即 HomeViewController,它有一个导航栏按钮,用户可以通过该按钮触发警报并输入字符串。这个字符串需要传递给子视图控制器。
这里是父视图控制器中的相关代码:
protocol NewSectionDelegate {
func sendSectionName(name : String)
}
class HomeViewController: UIViewController {
var sectionNameDelegate : NewSectionDelegate?
func addCardAsChild() { // add the child VC to the parent VC
if cardViewController == nil {
cardViewController = CardViewController()
addViewController(newViewController: cardViewController!)
} else {
addViewController(newViewController: cardViewController!)
}
}
func triggerAlert() {
let alertController = UIAlertController(title: "New section", message: "Name the section with a words or a sentence", preferredStyle: .alert)
alertController.addTextField(configurationHandler:
{(_ textField: UITextField) -> Void in //txtview customization
})
let addAction = UIAlertAction(title: "Add", style: .default) { _ in
guard let sectionName = alertController.textFields?.first?.text else { return }
self.sectionNameDelegate?.sendSectionName(name: sectionName) // Sending string; verified that the string is not nil
}
alertController.addAction(addAction)
self.present(alertController, animated: true, completion: nil)
}
这是子视图控制器:
class CardViewController: UIViewController, NewSectionDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let homeViewController = HomeViewController()
homeViewController.sectionNameDelegate = self
}
func sendSectionName(name: String) {
print("received name:\(name)") // This line of code is never called
}
数据没有通过,我不知道为什么。
【问题讨论】:
-
您在使用情节提要吗?如果是,
HomeViewController()不是您期望的实例。 -
没有。这都是程序化的。
-
尽管如此,您正在创建
HomeViewController的实例,然后设置委托并丢弃该实例。 -
那么问题是我应该把代码放在哪里?我试过 viewDidAppear 但这也不起作用。