有 2 个 Controller 。 this is how the UI looks this is how I am creating the popup i.e. using segue
HomeViewController: 有一个标签和一个按钮。单击名为 -->“添加操作”--> 的按钮后,将打开一个弹出窗口。
PopupViewController: 是一个弹出窗口,用户可以在其中输入内容并点击保存。在弹出窗口中,有一个文本字段。用户填写该字段并单击“保存”。 保存后 --> 为此 PopupViewController 调用 IBAction,该 Controller 具有 Dismiss() 函数来关闭弹出窗口。 解雇函数内的完成 block 是我尝试实例化 HomeViewController 来更新标签的地方。 (注意:PopupViewController 是通过 segue 创建的,通过选择当前上下文)
但是在这样做时,我发现 HomeViewController 内的所有 IBOutlet 在尝试从弹出窗口保存时均为零,因此我无法更新标签。
我尝试过的: 我查了网上的其他问答并验证如下: 1.我已经检查了标签与 Storyboard的连接。这是正确的。 2.我使用instantiateViewController语法来实例化 HomeViewController 正确。 但问题仍然存在。
HomeViewController
var actionNames = [String]()
var actionDescriptions = [String]()
@IBOutlet weak var firstActionLabel: UILabel!
func updateViewWithNewAction() {
print("updating views started")
if firstActionLabel != nil {
if actionNames.count > 0 {
firstActionLabel.text = actionNames[0]
} else {
print("no actions in the array")
}
} else {
print("firstActionLabel is nil")
}
print("updating views completed")
}
func addActions(actionName: String, actionDescription: String) {
actionNames.append(actionName)
actionDescriptions.append(actionDescription)
print("actions added")
}
PopupViewController
@IBOutlet weak var actionTitle: UITextField!
@IBOutlet weak var actionDescriptionTextView: UITextView!
@IBAction func createAction(_ sender: Any) {
//getting action values from user
actionName = actionTitle.text!
actionDescription = actionDescriptionTextView.text!
dismiss(animated: true, completion: {
print("completion block started ---")
let homeVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
homeVC.addActions(actionName: self.actionName, actionDescription: self.actionDescription)
homeVC.updateViewWithNewAction()
print("completion block ended ---")
})
}
预期结果:在 PopupViewController 的 createAction() 上,HomeViewController 内的标签应使用新值进行更新。 实际结果:在 homeVC.updateViewWithNewAction() 期间,firstActionLabel 为零
最佳答案
基本上我认为你想要这样的东西:
添加HomeViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let popupViewController = segue.destination as? PopupViewController {
popupViewController.callback = self.addActions
}
}
并在PopupViewController
中添加
var callback: ((String, String) -> Void)?
然后在PopupViewController
中更改
@IBAction func createAction(_ sender: Any) {
//getting action values from user
actionName = actionTitle.text!
actionDescription = actionDescriptionTextView.text!
dismiss(animated: true, completion: {
callback?(self.actionName, self.actionDescription)
})
}
关于ios - 从另一个 Controller (弹出窗口)访问它时,UILabel(作为 socket )保持为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53911354/