【问题标题】:From a containerView, how do you access the view controller containing the container in Swift?在 Swift 中,如何从 containerView 访问包含容器的视图控制器?
【发布时间】:2018-03-24 03:31:35
【问题描述】:

我确实有 4 个带有 Headerpart 的视图,我将其外包到一个容器视图中,以便在所有 4 个视图上具有相同的字段和布局。在我的容器中,我有很多标签,我知道这些标签要填充数据。我现在的问题是,我必须根据用户选择的游戏相应地填写标签。游戏是我的玩家类中的一个枚举。我不知道如何从容器视图中获取该信息并相应地设置游戏变量以执行我的代码。是否有解决方案可以从我的容器视图所在的视图中获取 storyboardid?


切换游戏

案例.Coinflip:

Player1PointsLabel.Text = (player1.points.coinflip)

案例.RollingDices

Player1PointsLabel.Text = (player1.points.rollingdices)


也许我做错了什么,设计方面,我还没有那么有经验,所以我也愿意提供建议。

最好的问候

【问题讨论】:

    标签: ios swift uicontainerview parentviewcontroller


    【解决方案1】:

    你问题的目标不是很明确。

    如果您想访问您的视图的超级视图(包含您的子视图的视图),请使用“myView.superview”。

    如果您想访问承载您的 UIViewController 的 UIViewController,请使用“myViewController.presentingViewController”。

    最后,如果你想访问承载你视图的 UIViewController,你必须遍历响应者链,直到到达第一个 UIViewController 或链的末端(UIView 是 UIResponder 的子类):

    func viewController(forView: UIView) -> UIViewController? {
      var nr = forView.next
      while nr != nil && !(nr! is UIViewController) {
        nr = nr!.next
      }
      return nr as? UIViewController
    }
    

    【讨论】:

      【解决方案2】:

      实现主控制器的prepareForSegue 方法。

      根据 segue 名称,您可以创建对 destination 控制器的引用,管理您的容器视图

      【讨论】:

        【解决方案3】:

        据我所知,获取插入到 ContainerView 中的视图的 ViewController 的唯一方法是在实例化 ContainerView 时在父 ViewController 中保存对它的引用。

        Swift 4 示例:

        如果您在情节提要中使用了 ContainerView 并添加了嵌入转场:

        var containerVC: UIViewController?
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if segue.identifier == "YourEmbedSegueName" {
                if let vc = segue.destination as? YourViewController {
                    self.containerVC = vc
                }
            }
        }
        

        或者,如果您以编程方式在 ContainerView 中插入了一个视图:

        var containerVC: UIViewController?
        func customContainerEmbed(vc: UIViewController) {
            self.addChildViewController(vc)
            yourContainer.addSubview(vc.view)
            vc.view.frame = yourContainer.bounds
            vc.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            vc.didMove(toParentViewController: self)
        
            self.containerVC = vc
        }
        

        【讨论】:

          猜你喜欢
          • 2014-02-10
          • 1970-01-01
          • 2013-03-20
          • 2016-07-22
          • 2012-10-28
          • 2016-02-13
          • 1970-01-01
          • 1970-01-01
          • 2018-05-04
          相关资源
          最近更新 更多