简体   繁体   English

在Swift中的视图控制器之间传递数据不起作用

[英]Passing data between view controllers in Swift does not work

Would you please help me? 你能帮我吗? The data (itemStr) is not passed even though the below code seems correct and I have already checked the similar questions on stack overflow.com: 即使以下代码似乎正确,数据(itemStr)也没有通过,并且我已经在stackoverflow.com上检查了类似的问题:

1st view controller (BookTableViewController.swift): 第一个视图控制器(BookTableViewController.swift):

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

2nd view controller (BookViewController.swift): 第二个视图控制器(BookViewController.swift):

var itemStr = String()

override func viewDidLoad() {
        super.viewDidLoad()

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

When I run the program, itemStr comes as nil. 当我运行程序时,itemStr为零。 I do not get "43"? 我没有得到“ 43”?

Thanks, in advance, for your kind help. 预先感谢您的帮助。 Guven 古文

You're running into problems because you're not really presenting the UIViewController that you think you are. 您遇到了问题,因为您没有真正呈现出您认为的UIViewController You're really presenting it's UINavigationViewController . 您实际上是在展示UINavigationViewController

But you could still do something like this: 但是您仍然可以执行以下操作:

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"        
        }        
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM