将相同的变量传递给具有不同值的容器视图

Passing same variable to container view with different value

我在主 viewController 上有一个按钮,其默认值 nildropDown pod 相关联。 在同一个 viewController 上还有一个容器视图。

在第一次加载时,我从共享首选项中获取变量的默认值,并通过 performSegue 将该值传递给容器视图。

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if(segue.identifier == "dataToContainerView"){
    DispatchQueue.main.async {

   var secondVC = segue.destination as! secondViewController //container viewController
        secondVC.variable = self.variable  
    }
  }
}

现在我需要通过用户从 dropdown 按钮中选择来再次传递相同变量的值。

 dropDown.selectionAction = { [unowned self] (index, item) in
        self.button.setTitle(item, for: UIControlState())
        self.variable = item
        print(item)
        self.performSegue(withIdentifier: "dataToContainerView", sender: nil)
  //performing segue to resend the new value of the variable.
    }

以上代码在 print(item) 之前都可以正常执行。 但是我在 performSegue 上收到以下错误。

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'There are unexpected subviews in the container view. Perhaps the embed segue has already fired once or a subview was added programmatically?

我应该如何在 dropDown pod 的帮助下第二次将值传递给容器视图以覆盖第一个值?

更新:- 我需要变量值,以便我可以将它传递给容器 viewController 上的 json 解析器。容器 viewController 上的代码重新执行。

您需要保存对嵌入式控制器的引用,以便稍后再次更新。在第一个 segue 中执行此操作:

// Declare a local variable in your parent container:
var secondVC: secondViewController!

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if(segue.identifier == "dataToContainerView"){
        DispatchQueue.main.async {
            self.secondVC = segue.destination as! secondViewController 
            //container viewController
            self.secondVC.variable = self.variable  
        }
    }
}

然后当您需要更新变量时,您可以直接引用它:

self.secondVC.variable = self.variable
self.secondVC.viewDidLoad()