我一直在尝试单独使用 Swift 以编程方式完成挑战——不使用 Storyboard。
我的第一个 View Controller 有一个标签和一个按钮可以转到第二个 View Controller 。
我在 app delegate
文件中创建了一个导航 Controller ,然后在按下按钮时推送到第二个 View Controller 。
第二个 View Controller 有一个文本框、一个保存文本的按钮和一个返回第一个 View Controller 的按钮。
UI 很好,但我不知道如何保存输入到第二个 View Controller 上的文本字段中的文本,然后在第一个 View Controller 的标签中显示该文本。
有人可以告诉我如何执行此操作吗?
目前在我的按钮中返回到第一个 View Controller 我有这个:
func handleBackToVC1() {
self.navigationController?.popViewController(animated: true)
}
这是我传递文本字段中的数据并将其显示在标签中的地方吗? 另外,我应该给标签一些文字作为开始吗?但是,哪些内容会更改为输入到文本字段中的内容?
最佳答案
使用协议(protocol)委托(delegate)将数据从 SecondViewController 传递到 FirstViewController
protocol TextFieldDataDelegate: class {
func saveText(_ text: String)
}
class SecondViewController: UIViewController {
weak var delegate: TextFieldDataDelegate?
//on save button tap call the delegate method
delegate?.saveText(textField.text)
}
//set FirstViewController as delegate for TextFieldDataDelegate protocol
class FirstViewController: UIController, TextFieldDataDelegate {
// when you create instance of SecondViewController assign the delegate as self
let secondVC = SecondViewController()
secondVC.delegate = self
//in saveText set label text as passed from SecondVC
func saveText(_ text: String) {
self.textLabel.text = text
}
}
注意:类似this这样的问题还有很多, 在提问之前总是搜索。谢谢
关于ios - 在第一个 View Controller 的标签中显示输入到文本字段(在第二个 View Controller 中)的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47453373/