2016-12-15 181 views
0

我有两个视图控制器,我必须将值从第二个vc传递到第一个vc。也就是说,必须在数组0123'中追加字符串nameText,这在我的firstvc中。这是我在secondvc正在做:无法在swift中传递视图控制器之间的值

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

我把一个破发点中的最后一条语句以上^做po homeViewController.nameArray.first我得到的值。但是当我做同样的控制回到第一个VC时,我尝试使用这个数组,说它是nil。我在这一行认为,homeViewController.nameArray.append(nameText),我在数组内添加一个值?这有什么问题?提前致谢。

+1

您正在实例化第一个视图控制器。 – paulvs

+0

那么有没有其他方法可以做到这一点? @paulvs –

回答

1

您的代码无法正常工作的原因,因为您正在实例化旧的viewcontroller并创建它的新实例。

您需要在此处创建委托/协议。例如:

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() 
     }  

    } 
相关问题