将新的Viewcontroller的视图添加为子视图

5

我尝试使用以下方法添加新的视图控制器视图,但失败了。这是唯一的呈现视图控制器的方式吗?不能从其他故事板的视图控制器视图中添加视图吗?

  //Working
    let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "customView") as! CustomViewController

    self.present( viewcontroller , animated: true, completion: nil)

    //Not working
    let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "customView") as! CustomViewController
    vc.view.frame = self.view.frame
    self.view.addSubview(vc.view)
1个回答

10
您需要在当前控制器中将CustomViewController作为ChildViewController添加进来。
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "customView") as! CustomViewController
vc.view.frame = self.view.bounds
self.addChildViewController(vc)
self.view.addSubview(vc.view)
vc.didMove(toParentViewController: self) //OR  vc.willMove(toParentViewController: self)

你错过了另一行。 - Anbu.Karthik
或使用vc.willMove(toParentViewController: self) - Anbu.Karthik
@Anbu.Karthik 为此进行了编辑。 - Nirav D
谢谢!我尝试将一些其他视图vc.customView添加到self.view中,但失败了。是否可能将具有定义框架的vc的一部分添加到self.view中,例如self.view.addsubview(vc.customview):vc来自storyboard? - Gobi M
@GobiM 我没有尝试过这样的事情,你试过添加了吗?vc.customview 还没有加载,所以可能会返回 nil。你可以简单地尝试一下来检查它。 - Nirav D
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接