如果将 AVPlayerViewController.showsPlaybackControls 设置为 false,则控件将根本不显示。即使你点击屏幕。
我希望控件一开始是隐藏的,但仍然能够通过点击来召唤它们。如果我将上述属性设置为 true,它们就会开始可见。 (是的,它们会在几秒钟后消失。)有没有办法开始隐藏,但仍然可以访问?
更新:我最终制作了自己的控件以实现更好的定制。这比较困难,但值得花时间。请阅读Apple的示例代码以供参考。它不仅涉及实现画中画,还涉及制作自定义控件:https://developer.apple.com/library/prerelease/ios/samplecode/AVFoundationPiPPlayer/Introduction/Intro.html
更新:点击时,AVPlayerViewController仅触发touchesBegan事件,而不触发touchesEnded事件。但这足以显示控件。
首先您需要隐藏控件。将此代码放在呈现 AVPlayerViewController 之前
YourAVPlayerViewController.showsPlaybackControls = false
然后子类化AVPlayerViewController并添加这个函数:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.showsPlaybackControls = true
super.touchesBegan(touches, withEvent: event)
}
旧解决方案:
我刚刚解决了这个问题。主要思想是在 AVPlayerViewController 之上放置一个 UIView 以接收点击手势,并在不再需要时隐藏该 UIView。
这是代码:
import AVKit
import UIKit
// Create a custom AVPlayerViewController
@available(iOS 8.0, *)
final class CustomAVPlayerViewController: AVPlayerViewController {
// Create a UIView to put on top of all
lazy var topView = UIView(frame: CGRectMake(0, 0, width, height))
override func viewDidLoad() {
super.viewDidLoad()
// For sure, set it to clearcolor
// (DON'T set alpha = 0 because it will stop receiving user interaction)
topView.backgroundColor = UIColor.clearColor()
// Add it to the view of AVPlayerViewController
self.view.addSubview(topView)
// Bring it to front
self.view.bringSubviewToFront(topView)
// Add a tap gesture recognizer
topView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "handleTap"))
}
// Handle the tap
func handleTap() {
// Show the control
self.showsPlaybackControls = true
// Hide the topView. You can unhide it when needed later.
self.topView.hidden = true
}
}
当您需要隐藏控件时,请执行以下操作:
var AVViewController = CustomAVPlayerViewController()
...
// Hide controls
AVViewController.showsPlaybackControls = false
// Show topView
AVViewController.topView.hidden = false
我想我已经使用动态手势识别器关系解决了这个问题。该解决方案避免了自定义控件(为了一致性),仅使用公共 API 并且不子类化
AVPlayerViewController
(这是明确禁止的,如其他答案中所述)。
具体方法如下:
制作一个嵌入
AVPlayerViewController
的容器视图控制器。 (无论控件如何,这都很有用,因为您需要将播放逻辑放在某处。)最初将
showsPlaybackControls
设置为 false
。添加 UITapGestureRecognizer 来识别初始点击。
在手势识别器的操作方法中,将
showsPlaybackControls
设置为 true
。到目前为止,它可以工作,但控件会在初次点击时立即消失。要解决此问题,请将您自己设置为手势识别器的委托,为任何其他单击手势识别器实现
gestureRecognizer:shouldBeRequiredToFailByGestureRecognizer:
并返回 true
。这是 Swift 中的实际实现;检查 andreyvit/ModalMoviePlayerViewController 存储库以获取最新代码:
import UIKit
import AVKit
import AVFoundation
public class ModalMoviePlayerViewController: UIViewController {
private let fileName: String
private let loop: Bool
private var item: AVPlayerItem!
private var player: AVPlayer!
internal private(set) var playerVC: AVPlayerViewController!
private var waitingToAutostart = true
public init(fileName: String, loop: Bool = true) {
self.fileName = fileName
self.loop = loop
super.init(nibName: nil, bundle: nil)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func viewDidLoad() {
super.viewDidLoad()
let url = NSBundle.mainBundle().URLForResource(fileName, withExtension: nil)!
item = AVPlayerItem(URL: url)
player = AVPlayer(playerItem: item)
player.actionAtItemEnd = .None
player.addObserver(self, forKeyPath: "status", options: [], context: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ModalMoviePlayerViewController.didPlayToEndTime), name: AVPlayerItemDidPlayToEndTimeNotification, object: item)
playerVC = AVPlayerViewController()
playerVC.player = player
playerVC.videoGravity = AVLayerVideoGravityResizeAspectFill
playerVC.showsPlaybackControls = false
let playerView = playerVC.view
addChildViewController(playerVC)
view.addSubview(playerView)
playerView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
playerView.frame = view.bounds
playerVC.didMoveToParentViewController(self)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ModalMoviePlayerViewController.handleTap))
tapGesture.delegate = self
view.addGestureRecognizer(tapGesture)
}
deinit {
player.pause()
player.removeObserver(self, forKeyPath: "status")
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func togglePlayPause() {
if isPlaying {
pause()
} else {
play()
}
}
func restart() {
seekToStart()
play()
}
func play() {
if player.status == .ReadyToPlay {
player.play()
} else {
waitingToAutostart = true
}
}
func pause() {
player.pause()
waitingToAutostart = false
}
var isPlaying: Bool {
return (player.rate > 1 - 1e-6) || waitingToAutostart
}
private func performStateTransitions() {
if waitingToAutostart && player.status == .ReadyToPlay {
player.play()
}
}
public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
performStateTransitions()
}
@objc func didPlayToEndTime() {
if isPlaying && loop {
seekToStart()
}
}
private func seekToStart() {
player.seekToTime(CMTimeMake(0, 10))
}
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if !playerVC.showsPlaybackControls {
playerVC.showsPlaybackControls = true
}
super.touchesBegan(touches, withEvent: event)
}
}
extension ModalMoviePlayerViewController: UIGestureRecognizerDelegate {
@IBAction func handleTap(sender: UIGestureRecognizer) {
if !playerVC.showsPlaybackControls {
playerVC.showsPlaybackControls = true
}
}
/// Prevents delivery of touch gestures to AVPlayerViewController's gesture recognizer,
/// which would cause controls to hide immediately after being shown.
///
/// `-[AVPlayerViewController _handleSingleTapGesture] goes like this:
///
/// if self._showsPlaybackControlsView() {
/// _hidePlaybackControlsViewIfPossibleUntilFurtherUserInteraction()
/// } else {
/// _showPlaybackControlsViewIfNeededAndHideIfPossibleAfterDelayIfPlaying()
/// }
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailByGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if !playerVC.showsPlaybackControls {
// print("\nshouldBeRequiredToFailByGestureRecognizer? \(otherGestureRecognizer)")
if let tapGesture = otherGestureRecognizer as? UITapGestureRecognizer {
if tapGesture.numberOfTouchesRequired == 1 {
return true
}
}
}
return false
}
}
thegathering的回答很好。我会重写touchesCancelled,这样控件就不会显示然后再次隐藏。
override public func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
super.touchesCancelled(touches, withEvent: event)
// toggle the player controls on if they were set to off
if !self.showsPlaybackControls {
self.showsPlaybackControls = true
}
}
在 Swift 3 中执行此操作的一个简单方法是设置
myController.showsPlaybackControls = false
,并使用按钮或手势识别器覆盖整个玩家视图。我将其嵌入故事板上另一个控制器的另一个视图中,以使其变得简单并且不会覆盖播放器控制器。技巧是在单击一次后隐藏按钮,因为播放器控制器此后将跟踪点击以显示/隐藏控件。
@IBAction func enableControls(button:UIButton)
{
controller?.showsPlaybackControls = true
button.isHidden = true //The button is only needed once, then the player takes over.
}
设置
showsPlaybackControls = false
,然后添加以下代码:
///Address insane Apple long-standing issue that you can't "launch it
///with no controls". There's no perfect solution.
var _firstTap = true
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if _firstTap {
showsPlaybackControls = true
_firstTap = false
return
}
super.touchesBegan(touches, with: event)
}
根据 Apple 文档,当播放器在屏幕上时,您不应该执行此操作
“当播放器视图控制器位于屏幕上时,请勿使用此属性更改播放控件的可见性。这样做会创建或销毁用户界面元素。”