我有一个segue,它是通过一个按钮触发的,该按钮在当前上下文中以模态方式显示另一个视图控制器。我使用自定义类来自定义转换,即:
class ShowAnimator: NSObject {
}
extension ShowAnimator: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard
let fromVC = transitionContext.viewController(forKey: .from),
let toVC = transitionContext.viewController(forKey: .to) else {
return
}
let containerView = transitionContext.containerView
containerView.insertSubview(fromVC.view, belowSubview: toVC.view)
let toFrame = transitionContext.finalFrame(for: toVC)
let screenBounds = UIScreen.main.bounds
let bottomLeftCorner = CGPoint(x: screenBounds.width, y: 0)
let finalFrame = CGRect(origin: bottomLeftCorner, size: screenBounds.size)
UIView.animate(withDuration: transitionDuration(using: transitionContext),
animations: {
fromVC.view.frame = finalFrame
},
completion: { _ in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
)
}
}
在我的主视图控制器中,我有以下相关功能:
let showAnimator = ShowAnimator()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destination = segue.destination
destination.transitioningDelegate = self
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return nil
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return showAnimator
}
请注意,此类是ViewController以及UIViewControllerTransitioningDelegate
但是,每当我按下按钮执行我的segue时,它都会正确地完成动画,但是一旦完成它就会显示一个黑屏,而不是下一个ViewController。
答案 0 :(得分:-1)
这一行存在一个问题:
containerView.insertSubview(fromVC.view, belowSubview: toVC.view)
您正在插入fromVC
视图。那是错的。它已经存在(虽然不一定在容器中)。
您不插入toVC
视图。那也是错的。你需要将它放入容器中。