以下是我用来以编程方式在视图中嵌入子视图控制器的辅助函数。
struct MyChildViewController {
static func embed(
viewControllerId: String,
storyboardName: String,
containerViewController: UIViewController,
containerView: UIView) -> UIViewController? {
guard let viewController = initViewController(viewControllerId, storyboardName: storyboardName)
else { return nil }
containerViewController.addChildViewController(viewController)
containerView.addSubview(viewController.view)
viewController.view.translatesAutoresizingMaskIntoConstraints = false
MyConstraints.fillParent(
viewController.view, parentView: containerView, margin: 0, vertically: true)
MyConstraints.fillParent(
viewController.view, parentView: containerView, margin: 0, vertically: false)
viewController.didMoveToParentViewController(containerViewController)
return viewController
}
static func initViewController(viewControllerId: String, storyboardName: String) -> UIViewController? {
let storyboard = UIStoryboard(name: storyboardName, bundle: NSBundle.mainBundle())
return storyboard.instantiateViewControllerWithIdentifier(viewControllerId)
}
}
struct MyConstraints {
static func fillParent(view: UIView, parentView: UIView, margin: CGFloat = 0,
vertically: Bool) -> [NSLayoutConstraint] {
var marginFormat = ""
if margin != 0 {
marginFormat = "-\(margin)-"
}
var format = "|\(marginFormat)[view]\(marginFormat)|"
if vertically {
format = "V:" + format
}
let constraints = NSLayoutConstraint.constraintsWithVisualFormat(format,
options: [], metrics: nil,
views: ["view": view])
parentView.addConstraints(constraints)
return constraints
}
}
用法:
let childWiewController = MyChildViewController.embed("MyViewControllerId", storyboardName: "MyStoryboardName", containerViewController: containerViewController, containerView: containerView)
在哪里:
- "MyViewControllerId" - 将被嵌入的子视图控制器的故事板 ID。
- “MyStoryboardName” - 带有嵌入式视图控制器的故事板文件的名称。
- containerView - 容器视图控制器中将嵌入子视图控制器的视图。