ios - 在 Swift 中的 View Controller 之间传递数据不起作用

标签 ios swift view controllers

你能帮帮我吗?数据 (itemStr) 没有传递,即使下面的代码看起来是正确的,我已经在 stack overflow.com 上检查过类似的问题:

第一个 View Controller (BookTableViewController.swift):

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      if let SecondController = segue.destination as? BookViewController {
            SecondController.itemStr = "43"        
        }        
}

第二个 View Controller (BookViewController.swift):

var itemStr = String()

override func viewDidLoad() {
        super.viewDidLoad()

        itemNoLabel?.text = "BNo:" + itemStr + " GYE"       
}

当我运行程序时,itemStr 为 nil。我没有得到“43”?

在此先感谢您的热心帮助。 居文

最佳答案

您遇到问题是因为您并没有像您认为的那样真正呈现 UIViewController。您真正呈现的是 UINavigationViewController

但是你仍然可以这样做:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      if let navigationViewController = segue.destination as? UINavigationController {

            guard let secondViewController = navigationViewController.topViewController as? BookViewController else { return }
            secondViewController.itemStr = "43"        
        }        
}

关于ios - 在 Swift 中的 View Controller 之间传递数据不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51161889/

相关文章:

iPhone iOS 在后台运行的应用程序会生成和处理通知吗?

ios - AWS Mobile hub with Cocoa pods Apple Mach-O 链接器错误

ios - 无法使用嵌入到我的项目中的 ios-charts 库分发内部构建

swift - 无法在 Playground 中可视化 UIBezierPath

ios - 未找到未过期的配置文件

ios - Firestore 添加文档 ||离线 ||打回来

ios - 自定义 View TextField 如何计算TextField总和

Android 通过 touchEvent 从类 View 完成 Activity

android - 防止 onDraw() 函数在配置更改期间重新启动

java - 将 Java 代码转换为 Model View Controller 架构模式