【发布时间】:2017-04-17 21:23:16
【问题描述】:
我正在创建一个具有根视图控制器的应用程序。这个根视图控制器是许多其他子视图控制器的父级,它们是应用程序中的主要状态。
由于我在根的viewDidLoad 的开头将子项添加到根,因此所有子项的 viewDid 和 viewWill 方法都会在添加到根时触发,而不是在我选择显示子视图控制器时触发。
有没有人知道在需要时避免孩子的 viewDid 或 viewWill 方法的好方法?如果没有,有没有办法对这些子视图控制器进行一些控制?请,谢谢!
根视图控制器:
override func viewDidLoad() {
super.viewDidLoad()
guard let storyboard = storyboard else {
print("ERROR: No storyboard found! Early return")
return
}
// Introduction
let introVC = storyboard.instantiateViewController(withIdentifier: "IntroID") as! IntroductionViewController
self.configureChildViewController(childController: introVC, onView: self.view)
// Login
let loginVC = storyboard.instantiateViewController(withIdentifier: "LoginID") as! LoginViewController
self.configureChildViewController(childController: loginVC, onView: self.view)
// Move to the first VC
self.goToVC(childVC: introVC)
}
移动到新的子视图控制器
func goToVC(childVC: UIViewController) {
// Bring child to front
self.view.bringSubview(toFront: childVC.view)
// Create the moveTo animations to the VC
childVC.didMove(toParentViewController: self)
}
子类的配置
extension UIViewController {
func configureChildViewController(childController: UIViewController, onView: UIView) {
if let view = childController.view {
// Add the view controller
addChildViewController(childController)
// Add and resize the subview
onView.addSubview(view)
constrainViewEqual(holderView: onView, view: view)
} else {
print("ERROR: The child controller has no usable view")
}
}
func constrainViewEqual(holderView: UIView, view: UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
// Create the view's new constraints
let pinTop = self.createConstraint(ofType: .top, inView: holderView, newView: view)
let pinBottom = self.createConstraint(ofType: .bottom, inView: holderView, newView: view)
let pinLeft = self.createConstraint(ofType: .left, inView: holderView, newView: view)
let pinRight = self.createConstraint(ofType: .right, inView: holderView, newView: view)
// Add the constraints
holderView.addConstraints([pinTop, pinBottom, pinLeft, pinRight])
}
private func createConstraint(ofType: NSLayoutAttribute, inView: UIView, newView: UIView) -> NSLayoutConstraint {
return NSLayoutConstraint( item: newView,
attribute: ofType,
relatedBy: .equal,
toItem: inView,
attribute: ofType,
multiplier: 1.0,
constant: 0)
}
【问题讨论】: