gpt4 book ai didi

ios - 在 Swift 中将字符串传递回之前的 View Controller 时遇到困难

转载 作者:行者123 更新时间:2023-11-30 13:18:56 27 4
gpt4 key购买 nike

我正在尝试使用委托(delegate)将字符串值传递回前一个 View Controller 。一切似乎都工作正常,除了由于某种原因,我发送回的字符串值没有显示在我想要的第一个 View Controller 的 UITextField 中。

这是我的相关代码:

ViewController“B”(将数据传递回前一个 View Controller 的 Controller ):

    protocol CountryFieldProtocol {
func setField(countryName: String)
}

class TableViewController: UITableViewController {

var countryProtocol: CountryFieldProtocol?
...

func dismiss() {

for item in countries {
if item.isSelected == true {
print("what is the country selected?" + item.name)
countryProtocol?.setField(item.name)
}
}

self.navigationController?.popViewControllerAnimated(true)
}

这是 View Controller “A”中的代码(从 View Controller “B”接收数据的代码):

func setField(countryName: String) {

textField.text = countryName
print("the country selected is:" + textField.text!)
}


@IBAction func textFieldEditing(sender: AnyObject) {

textField.resignFirstResponder()
let tableViewController = self.storyboard?.instantiateViewControllerWithIdentifier("CountryList") as? TableViewController
tableViewController?.countryProtocol = self
self.navigationController?.pushViewController(tableViewController!, animated: true)

}

在上面的代码中,当用户选择文本字段时,将调用第二个 View Controller 。然后,用户将被带到 UITableView,用户可以在其中从列表中选择一个项目。做出选择后,用户单击导航栏中的“完成”按钮,并且应该返回到第一个 View Controller 。

理论上,应该发生的情况是用户从列表中选择的内容应该出现在第一个 View Controller 的文本字段中。不幸的是,虽然选择从第一个 View Controller 中的 setField 函数打印到控制台,但该字符串不会出现在 textField 中。谁能看出我做错了什么吗?

最佳答案

Countryprotocol 被声明为可选且从未实例化,因此 setField() 永远不会被调用,因为 CountryProtocol 为 nil。

您应该“填充”该变量,最好的位置是第一个 View Controller 转场。

关于ios - 在 Swift 中将字符串传递回之前的 View Controller 时遇到困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37955576/

27 4 0