我正在尝试将警报文本字段中的数据传递给另一个 VC 的变量。
这是我的警报 Controller 。
let alert = UIAlertController(title: "Download URL", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Download", style: .default) { (action) in
guard let textField = alert.textFields?.first else {return}
self.ayb = textField.text ?? "Blank"
UserDefaults.standard.set(self.ayb, forKey: "urlString")
self.performSegue(withIdentifier: "segAdd", sender: self)
}
let secondAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addTextField { (actionTextField) in
actionTextField.placeholder = "Paste link here"
}
alert.addAction(action)
alert.addAction(secondAction)
present(alert, animated: true, completion: nil)
}
这是我用于传递数据的准备函数。override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segAdd" {
let destinationVC = tabBarController?.viewControllers?[0] as? BrowserWebViewController
destinationVC?.urlFromDownloads = self.ayb
print("The value of destinationVC?.urlFromDownloads is \(destinationVC?.urlFromDownloads)")
}
}
在控制台中,它会写“destinationVC?.urlFromDownloads 的值是\Optional("Text I typed in textField")”。但在 BrowserWebViewController 我的
"urlFromDownloads" is = ""(which is default)
.注意:Segue 的名字是真实的。
最佳答案
首先,不要声明额外的属性或将值保存到 UserDefaults
您可以在 sender
中传递字符串范围
let action = UIAlertAction(title: "Download", style: .default) { (action) in
guard let textField = alert.textFields?.first else {return}
self.performSegue(withIdentifier: "segAdd", sender: textField.text!)
}
您确定目标 View Controller 的方法是错误的。询问 segue
对于destination
.你可以强制向下转换类型。如果 segue 设计正确,则代码不得崩溃。override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segAdd" {
let destinationVC = segue.destination as! BrowserWebViewController
destinationVC.urlFromDownloads = sender as! String
print("The value of destinationVC?.urlFromDownloads is \(destinationVC.urlFromDownloads)")
}
}
关于ios - 准备 segue 函数无法将数据传递给另一个 VC Swift,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63203666/