从containerView,如何在Swift中访问包含容器的视图控制器?

时间:2017-10-12 09:00:45

标签: ios swift uicontainerview parentviewcontroller

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

切换游戏

case .Coinflip:

Player1PointsLabel.Text =(player1.points.coinflip)

case .RollingDices

Player1PointsLabel.Text =(player1.points.rollingdices)

也许我做错了什么,设计明智,我还没有经验,所以我也愿意接受建议。

祝你好运

3 个答案:

答案 0 :(得分:10)

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

Swift 4示例:

如果您在故事板中使用了ContainerView并添加了嵌入segue:

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中插入View:

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
}

答案 1 :(得分:1)

The goal of your question is not very clear.

If you want to access the superview of your view (the view containig your subview), then use 'myView.superview'.

If you want to access the UIViewController that host your UIViewController, then use 'myViewController.presentingViewController'.

Finally, if you want to access the UIViewController hosting your view, you must walk the responder chain until you reach the first UIViewController or the end of the chain (UIView is a subclass of UIResponder):

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

答案 2 :(得分:1)

Implement the prepareForSegue method of your main controller.

Based on the segue name, you can create a reference to the destination controller, managing you container view