在 iOS 中,如何以编程方式添加视频视图,然后在使用 Swift 完成播放后将其删除? [英] In iOS how do I programmatically add a video view and then remove it after it finishes playing using Swift?

查看:22
本文介绍了在 iOS 中,如何以编程方式添加视频视图,然后在使用 Swift 完成播放后将其删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在您进入主视图之前,我正在尝试为应用制作一个小介绍视频.代码如下:

I'm trying to make a little intro video for an app before you land on the main view. Code as follows:

import UIKit
import MediaPlayer

class ViewController: UIViewController {

    var moviePlayer: MPMoviePlayerController?
    //var player: MPMoviePlayerController?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        playVideo()
        self.view.removeFromSuperview()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



    func playVideo() {
        let path = NSBundle.mainBundle().pathForResource("paint-me_intro", ofType:"mp4")
        let url = NSURL.fileURLWithPath(path!)
        moviePlayer = MPMoviePlayerController(contentURL: url)
        if let player = moviePlayer {
            player.view.frame = self.view.bounds
            player.controlStyle = .None
            player.prepareToPlay()
            player.scalingMode = .AspectFit
            self.view.addSubview(player.view)
        }
    }
}

我想让它做的就是在视频播放完毕后,它需要消失.就这样.在我把脸撞到墙上之前,任何帮助将不胜感激.

All I want it to do is after the video finishes playing, it needs to go away. That's all. Any help would be greatly appreciated before I smash my face against the wall.

推荐答案

MPMoviePlayerController 使用通知进行消息传递,这与许多其他类的委托/协议模式不同.无论如何,回答你的问题.在您的视图中为适当的通知添加一个观察者确实加载,并指向一个删除视图的函数.

MPMoviePlayerController uses notifications for message passing, unlike the delegate/protocol pattern of so many other classes. Regardless, to answer your question. Add an observer for the appropriate notification in your view did load, and point to a function which removes the view.

添加观察者

NSNotificationCenter.defaultCenter().addObserver(self, selector: "movieFinished", name:
        MPMoviePlayerPlaybackDidFinishNotification, object: nil)

以及删除它的功能.

func movieFinished() {
    moviePlayer!.view.removeFromSuperview()
    NSNotificationCenter.defaultCenter().removeObserver(self, name: MPMoviePlayerPlaybackDidFinishNotification, object: nil)
}

这篇关于在 iOS 中,如何以编程方式添加视频视图,然后在使用 Swift 完成播放后将其删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆