效果如下
在First和Second上2个按钮点击调用switchover()
weak var currentViewController :UIViewController!
override func viewDidLoad() {
super.viewDidLoad()
currentViewController = FirstViewController()
self.addChildViewController(currentViewController)
self.view.addSubview(currentViewController.view)
}
private var first :Bool = true
//按钮点击事件
func switchover(){
let toVc = first ? SecondViewController() : FirstViewController()
self.addChildViewController(toVc)
toVc.view.top = UIScreen.main.bounds.height
self.transition(from: currentViewController, to: toVc, duration: 0.25, options: .curveLinear, animations: {
toVc.view.top = 0
}, completion: { finish in
self.currentViewController.didMove(toParentViewController: self)
self.currentViewController.removeFromParentViewController()
self.currentViewController = toVc
})
self.first = !first
}
动画可以自己修改,也可以支持多个控制器,自己维护ChildViewControllers。最好不要让ViewController长期持有子控制器,对内存不够友好。