我有以下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().
如何在出路时移除视图的动画以及在路上添加的视图?
解决方法
不同子视图控制器之间的动画: –
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) } }
在上面,
> oldViewController: – 当前显示的子viewController
> newViewController: – 将要添加的新子视图控制器
> containerView: – 显示所有子控制器的视图.
要为子视图设置动画,可以根据要求将transitionFlipFromLeft替换为可用的UIViewAnimationOptions,以使用不同类型的动画样式.