我想将 UIViewController 嵌入到 UIView 中。我想以编程方式创建它。我已经在故事板中创建了 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)获取宽度和高度的问题?
正如其他人所说,您不能在视图中嵌入视图控制器视图。 您可以做的是将
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)
编辑
要更改子视图控制器的显示方式和位置,只需更新其框架即可。
例如,使其高度为一半并固定在底部:
controller.view.frame = CGRect(x: 0, y: view.center.y, width: view.size.width, height: view.size.height * 0.5)
更新到最新的 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)
}
}
您可以使用通用方法,例如:
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)
}
希望有帮助