我有以下2个函数来添加和删除从容器视图控制器触发的子视图控制器:
@discardableResult func addChildViewController(withChildViewController childViewController: UIViewController) -> UIViewController {
// Add Child View Controller
addChildViewController(childViewController)
childViewController.beginAppearanceTransition(true, animated: true)
// Add Child View as Subview
view.addSubview(childViewController.view)
// Configure Child View
childViewController.view.frame = view.bounds
childViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// Notify Child View Controller
childViewController.didMove(toParentViewController: self)
return childViewController
}
@discardableResult func removeChildViewController(withChildViewController childViewController: UIViewController) -> UIViewController {
// Notify Child View Controller
childViewController.willMove(toParentViewController: nil)
childViewController.beginAppearanceTransition(false, animated: true)
// Remove Child View From Superview
childViewController.view.removeFromSuperview()
// Notify Child View Controller
childViewController.removeFromParentViewController()
return childViewController
}
上面的函数是UIViewController的扩展,所以我所做的就是父视图控制器上的self.addChildViewController()和self.removeChildViewController()。
如何在出路时移除视图并为其添加视图?
答案 0 :(得分:4)
不同子视图控制器之间的动画: -
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 100%; height: 500px;"></div>
在上面,
要为子视图设置动画,您可以根据要求将 transitionFlipFromLeft 替换为可用的 UIViewAnimationOptions ,以使用不同类型的动画样式。
答案 1 :(得分:0)
Sagar的答案不完整addSubview
方法在那里丢失
这是完整答案
func cycleFromViewController(oldViewController: UIViewController, toViewController newViewController: UIViewController) {
oldViewController.willMove(toParentViewController: nil)
newViewController.view.translatesAutoresizingMaskIntoConstraints = false
self.addChildViewController(newViewController)
self.addSubview(subView: newViewController.view, toView:self.containerView!)
newViewController.view.alpha = 0
newViewController.view.layoutIfNeeded()
UIView.animate(withDuration: 0.5, delay: 0.1, options: .transitionFlipFromLeft, animations: {
newViewController.view.alpha = 1
oldViewController.view.alpha = 0
}) { (finished) in
oldViewController.view.removeFromSuperview()
oldViewController.removeFromParentViewController()
newViewController.didMove(toParentViewController: self)
}
}
//--------------------------------------------------------------------------------
private func addSubview(subView:UIView, toView parentView:UIView) {
self.view.layoutIfNeeded()
parentView.addSubview(subView)
subView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor).isActive = true
subView.topAnchor.constraint(equalTo: parentView.topAnchor).isActive = true
subView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor).isActive = true
subView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor).isActive = true
}
希望对某人有帮助