您可以实现简单的协议,并将其用于您的视图:
protocol PresentedAsPush {
func presentLikeAPush()
}
extension UIView: PresentedAsPush {
func presentLikeAPush() {
self.frame = CGRect(x: bounds.width, y: 0, width: bounds.width, height: bounds.height)
UIView.animate(withDuration: 5) { [weak self] in // configure slide animation duration, and handler, if you need
guard let wrappedSelf = self else { return }
wrappedSelf.frame = CGRect(x: 0, y: 0, width: wrappedSelf.bounds.width, height: wrappedSelf.bounds.height)
}
}
}
推送代码:
func pushView() {
let blueView = UIView(frame: view.bounds)
blueView.backgroundColor = UIColor.blue
view.addSubview(blueView)
blueView.presentLikeAPush()
}
在您的情况下,您只需使用:
toController.view.presentLikeAPush()
您也可以为 presentLikeAPushMethod 实现处理程序,并在其中返回动画完成块,并在动画之后执行您需要的操作(删除旧控制器等)
您还可以使用约束代替框架。
添加完整代码:
class RootViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.green
let redVc = RedViewController()
addChild(redVc)
view.addSubview(redVc.view)
}
}
class RedViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.red
let pushButton = UIButton()
view.addSubview(pushButton)
pushButton.setTitle("push", for: .normal)
pushButton.frame = CGRect(x: 20, y: 100, width: 100, height: 50)
pushButton.addTarget(self, action: #selector(pushButtonPressed), for: .touchUpInside)
}
@objc private func pushButtonPressed() {
guard let parent = parent else { return }
let blueVc = BlueViewController()
parent.addChild(blueVc)
parent.view.addSubview(blueVc.view)
blueVc.view.presentLikeAPush(fromController: self)
}
}
class BlueViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.blue
}
}
protocol PresentedAsPush {
func presentLikeAPush(fromController: UIViewController)
}
extension UIView: PresentedAsPush {
func presentLikeAPush(fromController: UIViewController) {
self.frame = CGRect(x: bounds.width, y: 0, width: bounds.width, height: bounds.height)
UIView.animate(withDuration: 2, animations: { [weak self] in
guard let wrappedSelf = self else { return }
wrappedSelf.frame = CGRect(x: 0, y: 0, width: wrappedSelf.bounds.width, height: wrappedSelf.bounds.height)
}) { (completed) in
fromController.view.removeFromSuperview()
fromController.removeFromParent()
fromController.willMove(toParent: nil)
}
}
}