【问题标题】:Embed UIViewController inside a UIView在 UIView 中嵌入 UIViewController
【发布时间】:2017-08-26 07:04:00
【问题描述】:

我想在 UIView 中嵌入 UIViewController。我想以编程方式创建它。我在情节提要中创建了 UIViewController。

我创建空 UIView 的代码:

let myNewView=UIView(frame: CGRect(x: (0 + screenHeight / 2), y: leftView.frame.origin.y, width: screenHeight / 2, height: leftView.frame.height))
myNewView.backgroundColor=UIColor.lightGray

self.view.addSubview(myNewView)

以及将 UIViewController 附加到视图的代码:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
var controller: UIViewController = storyboard.instantiateViewController(withIdentifier: "testView") as UIViewController
myNewView.addSubview(controller.view)

这会在我的 UIView 中显示视图,但方式不正确。 UIView 在这种情况下是 512 像素宽。而(嵌入的)UIViewcontroller 认为它是 1024 像素宽(全屏宽度)。

如何解决嵌入视图从其父级(UIView)获取宽度和高度的问题?

【问题讨论】:

  • 你所做的是完全错误的。您不能以这种方式简单地将视图控制器的视图添加到您的界面中。 (至于大小,为添加的视图提供frame 取决于您。但无论如何您的视图都无法正常工作。)
  • @matt 这样做的好方法是什么?

标签: swift uiview uicontainerview


【解决方案1】:

正如其他人所说,您不能在视图中嵌入视图控制器视图。 您可以做的是将ViewController 嵌入到另一个ViewController 中作为ChildViewController

尝试将 newView 代码替换为:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
var controller: UIViewController = storyboard.instantiateViewController(withIdentifier: "testView") as UIViewController

//add as a childviewcontroller
 addChildViewController(controller)

 // Add the child's View as a subview
 self.view.addSubview(controller.view)
 controller.view.frame = view.bounds
 controller.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]

 // tell the childviewcontroller it's contained in it's parent
  controller.didMove(toParentViewController: self)

编辑: 要更改 childviewcontroller 的显示方式和位置,只需更新其框架。 例如使其高度减半并固定在底部:

controller.view.frame = CGRect(x: 0, y: view.center.y, width: view.size.width, height: view.size.height * 0.5) 

【讨论】:

  • 但是如何在某个位置添加新的视图控制器呢?例如仅在屏幕的一半上?
  • @da1lbi3 您可以通过更新框架来更改原点和大小。查看我编辑的答案
【解决方案2】:

更新到最新的 swift 并使用 UIViewController 类的扩展:

extension UIViewController {
    func embed(_ viewController:UIViewController, inView view:UIView){
        viewController.willMove(toParent: self)
        viewController.view.frame = view.bounds
        view.addSubview(viewController.view)
        self.addChild(viewController)
        viewController.didMove(toParent: self)
    }
}

【讨论】:

    【解决方案3】:

    你可以有一个通用的方法,比如:

    func embed(_ viewController:UIViewController, inParent controller:UIViewController, inView view:UIView){
       viewController.willMove(toParent: controller)
       viewController.view.frame = view.bounds
       view.addSubview(viewController.view)
       controller.addChild(viewController)
       viewController.didMove(toParent: controller)
    }
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2020-12-11
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      • 2010-11-12
      • 2019-08-14
      相关资源
      最近更新 更多