委派iOS中未调用自定义视图类的事件

时间:2016-01-12 00:10:27

标签: ios swift youtube delegates interface-builder

我正在尝试使用

播放YouTube视频

Swift-Youtube-Player

我当前遇到了没有调用委托方法的问题。

我已经从IB为这个播放器创建了一个插座,但由于某些原因我无法将代理从IB拖到视图控制器中,因此我尝试在代码中执行此操作。

这就是我的尝试:

@IBOutlet weak var youtubePlayer: YouTubePlayerView!

    var _currentYoutubeId: String = "";

    override func viewDidLoad() {
        super.viewDidLoad()
        print(_currentYoutubeId)
        youtubePlayer.delegate = self
    }

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

    func playerReady(videoPlayer: YouTubePlayerView) {
        print(videoPlayer)
        if youtubePlayer.ready {
            youtubePlayer.playerVars = [
                "playsinline": "1",
                "controls": "0",
                "showinfo": "0"
            ]
            youtubePlayer.loadVideoID(_currentYoutubeId)
            if youtubePlayer.playerState != YouTubePlayerState.Playing {
                youtubePlayer.play()
            } else {
                youtubePlayer.pause()
            }
        }

    }

    func playerStateChanged(videoPlayer: YouTubePlayerView, playerState: YouTubePlayerState) {
        print("promjena")
    }

    func playerQualityChanged(videoPlayer: YouTubePlayerView, playbackQuality: YouTubePlaybackQuality) {
        print("promjena")
    }

我在最新的XCode版本中这样做,我对iOS,Swift和Apple相关的一切都很新。

具体来说,我的问题是如何将此委托连接到播放器以便调用其生命周期方法?

编辑:我以前使用UICollectionViewDelegate设法完成此操作,但我没有成功使用此自定义视图。

1 个答案:

答案 0 :(得分:0)

这是我使用Swift-Youtube-Player的方式。

class videoController: UIViewController, YouTubePlayerDelegate {
@IBOutlet var videoPlayer: YouTubePlayerView!
var videoID: String?

override func viewDidLoad() {
    super.viewDidLoad()

    videoPlayer.delegate = self

    if let videoID = self.videoID {
        videoPlayer.loadVideoID(videoID)
    }
}

func playerReady(videoPlayer: YouTubePlayerView) {
    videoPlayer.play()
}

func playerStateChanged(videoPlayer: YouTubePlayerView, playerState: YouTubePlayerState) {
    if videoPlayer.playerState == YouTubePlayerState.Ended || videoPlayer.playerState == YouTubePlayerState.Paused {
        //Your code here
    } 
}

func playerQualityChanged(videoPlayer: YouTubePlayerView, playbackQuality: YouTubePlaybackQuality) {
    //Your code here
}

}