【问题标题】:Multiple Container Views with Delegates具有委托的多个容器视图
【发布时间】:2019-05-08 20:17:21
【问题描述】:

我有一个包含 2 个容器视图的视图控制器。其中一个有滚动视图,其中一个只是一个小视图。

现在,我想在所有 3 个之间进行通信,我这样做的方式是使用主 ViewController 作为其他 2 个的委托。我最初不知道如何将它们设置为委托,因为没有过渡或其他人的介绍(他们就在那里)

几个月前在这里询问后,我得到了以下答案:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "embedSegue") {
        resultsVC = (segue.destination as! GoalsVC)
        resultsVC.calcDelegate = self
    }
}

但是,我不知道如何为 BOTH 包含的视图执行此操作。他们都使用相同的 segue,所以我不能让他们都拥有相同的 ViewController。

我在考虑使用情节提要 ID,但如何在 prepareforsegue 中引用它们? 会不会像

if (segue.identifier == "embedSegue" && storyboardidentifier = "myVC1") {
    resultsVC = (segue.destination as! GoalsVC)
    resultsVC.calcDelegate = self
} else if (segue.identifier == "embedSegue" && storyboardidentifier = "myVC2") {
    otherVC = (segue.destination as! NewVC)
    resultsVC.calcDelegate = self
}

除了我不知道引用故事板的确切代码

【问题讨论】:

    标签: ios delegates segue uicontainerview


    【解决方案1】:

    如果你使用 ?代替 !您可以使用转换成功来指示您是否拥有正确的视图控制器。代码如下

    if segue.identifier == "embedSegue" {
        if let resultsVC = segue.destination as? GoalsVC {
            resultsVC.calcDelegate = self
        }
        if let otherVC = segue.destination as? NewVC {
            resultsVC.calcDelegate = self
        }
    }
    

    您可以通过委托设置来进一步简化此代码。设置一个新的委托,确保你的两个嵌入式视图控制器符合它。在下面的代码中,我假设您已经编写的委托名为 CalcDelegate。

    protocol CalcDelegateDelegate {
        var calcDelegate : CalcDelegate? {get set}
    }
    
    class GoalsVC : UIViewController, CalcDelegateDelegate {
        var calcDelegate: CalcDelegate? = nil
    }
    
    class NewVC : UIViewController, CalcDelegateDelegate {
        var calcDelegate: CalcDelegate? = nil
    }
    

    然后你的准备代码被简化为

    if segue.identifier == "embedSegue" {
        if var delegate = segue.destination as? CalcDelegateDelegate {
            delegate.calcDelegate = self
        }
    }
    

    任何嵌入在主控制器中的新视图控制器只需要符合委托,它会自动获取 calcDelegate 并可以与您的其他视图控制器通信。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多