简体   繁体   English

无法迅速在视图控制器之间传递值

[英]Not able to pass values between viewcontrollers in swift

I have two viewcontrollers, I have to pass values from the second vc to the first vc. 我有两个viewcontrollers,我必须将值从第二个vc传递到第一个vc。 That is, have to append the string nameText in the array nameArray , which is in my firstvc. 也就是说,必须将字符串nameText附加在我的firstvc中的数组nameArray中。 This is what I'm doing in my secondvc: 这是我在secondvc中所做的:

let homeViewController: HomeViewController = storyboard?.instantiateViewController
(withIdentifier: "homeViewControllerIdentifier") as! HomeViewController
homeViewController.nameArray.append(nameText)

I put a break point in the last statement above^ and do po homeViewController.nameArray.first I get the value. 我在上面的最后一条语句中放置了一个断点^,然后执行po homeViewController.nameArray.first我得到了该值。 But when I do the same when the control goes back to the first vc, And I try and use the array, is says it is nil . 但是当控件返回第一个vc时执行相同的操作时,我尝试使用该数组,即为nil I thought in this line, homeViewController.nameArray.append(nameText) , I'm adding a value inside an array? 我以为这是homeViewController.nameArray.append(nameText)这行,我要在数组内添加值吗? What is wrong in this? 这有什么问题? Thanks in advance. 提前致谢。

Reason why your code isn't working because you're instantiating the old viewcontroller and creating a new instance of it. 您的代码之所以无法运行的原因是因为您要实例化旧的viewcontroller并创建一个新的实例。

You need to create a delegate/protocol here. 您需要在此处创建一个委托/协议。 Something like: 就像是:

    protocol ViewDelegate{
       func updateArray()
    }

    class Class1: UIViewController{

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destinationController as! Class2
        vc.delegate = self
    }
     }    
    extension Class1: ViewDelegate {

    func updateArray(){
    // update array here
       }
    }

    class Class2: UIViewController{
    var delegate: ViewDelegate!

     func updatearrayhere(){
        delegate.updateArray()
       }    

    }

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

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