Pan*_*ngu 5 ios avplayer swift avplayerviewcontroller
我试图检测何时处于AVPlayerViewController全屏模式,但我很难做到这一点。我想知道用户何时选择展开按钮进入全屏,如下所示:
我已经根据这些建议添加了适当的观察者:
相应的代码:
var avWidth:CGFloat = 375
var avHeight:CGFloat = 300
override func viewDidLoad()
{
super.viewDidLoad()
let path = NSBundle.mainBundle().pathForResource("cable pressback", ofType: "mp4")
let url = NSURL.fileURLWithPath(path!)
let player = AVPlayer(URL: url)
playerViewController.player = player
playerViewController.view.frame = CGRectMake(0, 100, self.view.frame.size.width, 300)
playerViewController.view.translatesAutoresizingMaskIntoConstraints = true
view.addSubview(playerViewController.view)
self.addChildViewController(playerViewController)
[playerViewController .addObserver(self, forKeyPath:"videoBounds" , options: NSKeyValueObservingOptions.New, context: nil)]
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>)
{
print("playerViewController.view.frame = \(playerViewController.view.frame)")
if keyPath == "videoBounds"
{
let rect = change!["new"]! as! NSValue
if let newrect = rect.CGRectValue() as CGRect?
{
if newrect.width > 0 || newrect.height > 0
{
if avWidth > 0 || avHeight > 0
{
if newrect.width > avWidth || newrect.height > avHeight
{
print("Full Screen")
}
else if newrect.width < avWidth || newrect.height < avHeight
{
print("Normal screen")
}
}
avWidth = newrect.width
avHeight = newrect.height
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,它似乎永远不会到达代码print("Full Screen")。print("Normal Screen")无论播放器处于正常模式还是全屏模式,它都会被击中。
谢谢!
从 iOS 12 开始,我们可以使用这些AVPlayerViewControllerDelegate委托方法:
func playerViewController(AVPlayerViewController, willBeginFullScreenPresentationWithAnimationCoordinator: UIViewControllerTransitionCoordinator)
func playerViewController(AVPlayerViewController, willEndFullScreenPresentationWithAnimationCoordinator: UIViewControllerTransitionCoordinator)
Run Code Online (Sandbox Code Playgroud)
更新为 Swift 3:
添加对象的观察者playerViewController:
playerViewController(self, forKeyPath: "videoBounds", options: NSKeyValueObservingOptions.new, context: nil)
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)
{
if keyPath == "videoBounds"
{
if let rect = change?[.newKey] as? NSValue
{
if let newrect = rect.cgRectValue as CGRect?
{
// 200 is height of playerViewController in normal screen mode
if newrect.size.height <= 200
{
print("normal screen")
}
else
{
print("full screen")
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7638 次 |
| 最近记录: |