ios - 准备 segue 函数无法将数据传递给另一个 VC Swift,

标签 ios swift xcode

我正在尝试将警报文本字段中的数据传递给另一个 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/

相关文章:

ios - UIAlertController 在生成警报 View 时出错

ios - 异步服务调用的 TableView 单元测试

ios - ReactiveCocoa 3 : Map signal to value (Swift)

ios - XCUI 测试 : How to click Labels populated at run time

iOS swift 自定义键盘未检测到 keyboardType

iphone - NSFetchedResultsController 错误 : 'NSInternalInconsistencyException' , 原因: 'no object at index 1 in section at index 0'

ios - = vs == 在 NSPredicate 中

ios - TableView 没有出现在模拟器中?

ios - 截取屏幕时显示警报并要求输入文本

objective-c - 当我想在变量更改时停止时如何在 xCode 中设置断点?