要从视频单元格转换到播放器控制器,您可以使用 AVPlayerLayer 和自定义动画,例如:
ViewController.swift
// Present player controller
let playerViewController = AVPlayerViewController()
playerViewController.player = player // Your current player instance
playerViewController.transitioningDelegate = self // Custom animation
self.present(playerViewController, animated: true, completion: nil)
extension ViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return PlayerAnimationController(playerLayer: playerLayer) // Your current player's layer
}
}
PlayerAnimationController.swift
class PlayerAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
let playerLayer: AVPlayerLayer
init(playerLayer: AVPlayerLayer) {
self.playerLayer = playerLayer
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let toView = transitionContext.view(forKey: .to) else { return }
let containerView = transitionContext.containerView
containerView.addSubview(toView)
let originalSuperlayer = playerLayer.superlayer
let originalFrame = playerLayer.frame
let frame = playerLayer.convert(playerLayer.bounds, to: nil)
containerView.layer.addSublayer(self.playerLayer)
// Start frame
CATransaction.begin()
CATransaction.setAnimationDuration(0)
CATransaction.setDisableActions(true)
self.playerLayer.frame = frame
CATransaction.commit()
toView.alpha = 0
DispatchQueue.main.async {
let duration = self.transitionDuration(using: transitionContext)
UIView.animateKeyframes(withDuration: duration, delay: 0) {
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1/2) {
self.playerLayer.frame = containerView.bounds
}
UIView.addKeyframe(withRelativeStartTime: 1/2, relativeDuration: 1/2) {
toView.alpha = 1.0
}
}
completion: { _ in
originalSuperlayer?.addSublayer(self.playerLayer)
self.playerLayer.frame = originalFrame
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
}
示例使用AVPlayerViewController,但您当然可以使用自己的。