我正在使用UIViewControllerAnimatedTransitioning
和UIPercentDrivenInteractiveTransition
来交互式地取消模态呈现的视图控制器。没有太多花哨的东西。但是我注意到在交互开始时偶尔会出现小故障。如果使用.curveEaseOut
选项进行动画处理,则会更加明显。在我跟随一些在线教程(https://www.thorntech.com/2016/02/ios-tutorial-close-modal-dragging/)时也会出现同样的问题。当我第一次向下拖动它时,您可以在 gif 中看到故障。有什么建议吗?
MyDismissAnimator
class SlideInDismissAnimator: NSObject, UIViewControllerAnimatedTransitioning {
// ...
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let toVC = transitionContext.viewController(forKey: .to),
let presentedVC = transitionContext.viewController(forKey: .from) else {return}
let presentedFrame = transitionContext.finalFrame(for: presentedVC)
var dismissedFrame = presentedFrame
dismissedFrame.origin.y = transitionContext.containerView.frame.size.height
transitionContext.containerView.insertSubview(toVC.view, belowSubview: presentedVC.view)
}
let duration = transitionDuration(using: transitionContext)
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
presentedVC.view.frame = dismissedFrame
}) { _ in
if transitionContext.transitionWasCancelled {
toVC.view.removeFromSuperview()
}
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
MyInteractor
class SwipeInteractionController: UIPercentDrivenInteractiveTransition {
var interactionInProgress = false
private var shouldCompleteTransition = false
private weak var viewController: UIViewController!
init(viewController: UIViewController) {
self.viewController = viewController
super.init()
let gesture = UIPanGestureRecognizer(target: self, action: #selector(handleGesture(_:)))
viewController.view?.addGestureRecognizer(gesture)
}
@objc func handleGesture(_ gestureRecognizer: UIPanGestureRecognizer) {
let translation = gestureRecognizer.translation(in: gestureRecognizer.view!.superview!)
var progress = (translation.y / viewController.view.bounds.height)
progress = CGFloat(fminf(fmaxf(Float(progress), 0.0), 1.0))
switch gestureRecognizer.state {
case .began:
interactionInProgress = true
viewController.dismiss(animated: true, completion: nil)
case .changed:
shouldCompleteTransition = progress > 0.3
update(progress)
case .cancelled:
interactionInProgress = false
cancel()
case .ended:
interactionInProgress = false
if shouldCompleteTransition {
finish()
} else {
cancel()
}
default:
break
}
}
}
animateTransition
函数吗?能否确保它从主线程调用? - mfaanianimateTransition
在dismiss动画器中,由UIKit自动调用。所以我猜这不是问题所在?让我知道你认为应该如何处理。 - Jack Guo