问题描述
我有以下2个函数,用于添加和删除从容器视图控制器触发的子视图控制器:
I have the following 2 functions that add and remove child view controllers triggered from a container view controller:
@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() 。
The functions above are extensions to UIViewController, so all I'm doing is self.addChildViewController() and self.removeChildViewController() on the parent view controller.
如何动画化视图在退出时被移除以及视图在进入时被添加?
How do I animate the view being removed on its way out and the view being added on its way in?
推荐答案
在不同子视图控制器之间进行动画处理:-
Animating between different child view controllers:-
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 (根据要求)。
To animate child view, you can use different type of animation style by replacing transitionFlipFromLeft to available UIViewAnimationOptions according requirement.
这篇关于在添加到容器视图控制器或从容器视图控制器中删除时,如何为子视图控制器设置动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!