2017-08-14 57 views
-1

我有一個包含一個按鈕的自定義單元格的表視圖。根據選擇按鈕的行,我想要播放特定的視頻文件。然而,現在我的代碼設置方式無論按下哪個按鈕都會顯示相同的視頻文件。我怎樣才能配置我的代碼,以確保每行顯示我喜歡的不同視頻?如何讓按鈕播放不同的視頻取決於它所在的行?

代碼表視圖:

import UIKit 
import AVKit 
import AVFoundation 

class DrillsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 

var player: AVPlayer? 
var arrayForKey2 = [[String]]() 
var keyIndex = Int() 
var headLabel = String() 
var labels = Array(trainingDict.keys) 

@IBOutlet weak var tableView: DrillsTableView! 

@IBOutlet weak var drillLabel: UILabel! 

@IBOutlet weak var labelBackground: UIView! 


@IBAction func back(_ sender: Any) { 
    performSegue(withIdentifier: "back", sender: self) 
} 



public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
{ 

    return arrayForKey2.count 
} 

func numberOfSections(in tableView: UITableView) -> Int { 
    return 1 
} 

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{ 
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell" , for: indexPath) as! DrillsTableViewCell 



    //clear background color needed in order to display gradient cell 
    cell.backgroundColor = UIColor.clear 

    //gradient configuration 
    gradient = CAGradientLayer() 
    gradient.frame = tableView.bounds 
    gradient.colors = [UIColor.black.cgColor, UIColor.darkGray.cgColor, UIColor.black.cgColor] 
    tableView.layer.insertSublayer(gradient, at: 0) 
    gradient.startPoint = CGPoint(x: 0.0, y: 0.0) 
    gradient.endPoint = CGPoint(x: 1.0, y: 1.0) 





//Possible method for 'drillLabel' gradient 
    //drillLabelGradient = CAGradientLayer() 
    //drillLabelGradient.frame = labelBackground.bounds 
    //drillLabelGradient.colors = [UIColor.red.cgColor, UIColor.darkGray.cgColor, UIColor.black.cgColor] 
    //labelBackground.layer.insertSublayer(drillLabelGradient, at: 0) 
    //drillLabelGradient.startPoint = CGPoint(x: 0.0, y: 0.0) 
    //drillLabelGradient.endPoint = CGPoint(x: 1.0, y: 1.0) 
    drillLabel.font = UIFont(name: "Symbol", size: 24.0) 

    //attributes for watch/play button 

    cell.playButton.layer.shadowColor = UIColor.black.cgColor 
    cell.playButton.layer.shadowOffset = CGSize(width: 2, height: 2) 
    cell.playButton.layer.shadowOpacity = 0.7 
    cell.playButton.layer.shadowRadius = 1 

    //details for cell label display 
    cell.borderWidth = 1.5 
    cell.borderColor = UIColor.white 
    cell.drillTitle.text = "\(arrayForKey2[keyIndex][indexPath.row])" 
    cell.drillTitle.font = UIFont(name: "Symbol", size: 18.0) 
    cell.drillTitle.textColor = UIColor.white 

    return cell 
} 




override func viewDidLoad() { 
    super.viewDidLoad() 
    tableView.delegate = self 
    tableView.dataSource = self 
    drillLabel.text = labels[keyIndex] 

     } 

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


} 

代碼表視圖單元格:

import UIKit 
    import AVFoundation 
    import AVKit 

    class VideoPlayerView: UIView { 

let pauseButton: UIButton = { 
    let button = UIButton(type: .system) 
    button.setImage(#imageLiteral(resourceName: "Triangle 2"), for: .normal) 
    button.translatesAutoresizingMaskIntoConstraints = false 
    button.tintColor = UIColor.white 
    button.isHidden = false 
    button.addTarget(self, action: #selector(handlePause), for: .touchUpInside) 

    return button 
}() 

var isPlaying = false 

func handlePause() { 
    if isPlaying { 
     player?.pause() 
    pauseButton.alpha = 1.0 } 

    else { player?.play() 
     pauseButton.alpha = 0.01 
    } 

    isPlaying = !isPlaying 
} 

//container view that holds sublayers for the video control objects 
let controlsContainerView: UIView = { 
    let view = UIView() 
    view.backgroundColor = UIColor(white: 0, alpha: 1.0) 
    return view 
}() 


override init(frame: CGRect) { 
    super.init(frame: frame) 

    setupPlayerView() 

    //configures container view (video's background) 
    controlsContainerView.frame = frame 
    addSubview(controlsContainerView) 
    backgroundColor = UIColor.black 


    //following adds pause/play button to video 
    controlsContainerView.addSubview(pauseButton) 
    pauseButton.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true 
    pauseButton.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true 


} 

var player: AVPlayer? 

//function that sets up video playback 
private func setupPlayerView() { 



    //variable that contains video url 
    let fileUrl = URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BlackHeartBB/dunk.mov") 




     player = AVPlayer(url: fileUrl) 

    //video only renders if you specify 'playerLayer' 
     let playerLayer = AVPlayerLayer(player: player) 
     self.layer.insertSublayer(playerLayer, at: 1) 
     playerLayer.frame = frame 


     player?.play() 


     //attached obeserver of 'player' to tell when 'player' is ready 
     player?.addObserver(self, forKeyPath: "currentItem.loadedTimeRanges", options: .new, context: nil) 

} 
//method called every time you add obserever to an object 
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { 
    //strring that lets AVPlayer know its ready 
    if keyPath == "currentItem.loadedTimeRanges" { 

     //configures container view while video is playing 
     controlsContainerView.backgroundColor = UIColor.clear 
     pauseButton.alpha = 0.05 
     isPlaying = true 

    } 
} 

required init?(coder aDecoder: NSCoder) { 
    fatalError("init(coder:) has not been implemented") 
} 

}

class DrillsTableViewCell: UITableViewCell { 

var videoURL:[URL] = [URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BlackHeartBB/dunk.mov"), URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BlackHeartBB/mk.MOV")] 
var video = URL(fileURLWithPath: String()) 


@IBOutlet weak var logoImage: UIImageView! 

@IBOutlet weak var drillTitle: UILabel! 


@IBOutlet weak var playButton: UIButton! 
@IBAction func watchButton(_ sender: Any) { 
    print(123) 


     //controls video background view 
     if let keyWindow = UIApplication.shared.keyWindow { 
      let view = UIView(frame: keyWindow.frame) 
      view.backgroundColor = UIColor.white 


      view.frame = CGRect(x: 0.0, y: 0.0, width: keyWindow.frame.width, height: keyWindow.frame.height) 

      let videoPlayerFrame = CGRect(x: 0, y: 0, width: keyWindow.frame.width, height: keyWindow.frame.width * 9/16) 
      let videoPlayerView = VideoPlayerView(frame: videoPlayerFrame) 
      view.addSubview(videoPlayerView) 


      keyWindow.addSubview(view) 
      UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseOut, animations: { 

        view.frame = keyWindow.frame 

      }, completion: { (completedAnimation) in 
       //possible features implemented later 
       UIApplication.shared.isStatusBarHidden = true 


      }) 



    } 

} 

}

+0

在定義屬性的cell called讓'videoUrl'並在你的cellForRow方法中傳遞url對應的索引路徑 –

+0

你可以舉一個使用代碼的例子嗎?你的解釋對於像我這樣的初學者來說太模糊了 –

+0

我對你的問題有點困惑,那就是爲什麼不回答,你需要在每個單元格中播放不同的視頻網址?和你的網址在你的ViewController中?請澄清我的這些問題,我會提供一個答案 –

回答

1

首先,你需要在你的VideoPlayerView添加CLAS與URL SA VAR你會在你的類

fileprivate var videoUrl : URL? 

播放和修改VideoPlayerViewsetupPlayerView方法傳遞的網址是這樣的

private func setupPlayerView(url:URL) 

之後,你需要在DrillsTableViewCell

替換該行
var videoURL:[URL] = [URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BlackHeartBB/dunk.mov"), URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BlackHeartBB/mk.MOV")] 
var video = URL(fileURLWithPath: String()) 

by this one

var videoURL:URL? 

並在watchButton動作你需要添加

videoPlayerView.setupPlayerView(self.videoURL!) 

之後,你就可以在你的cellForRowAtIndexPath加入這一行

if let urlValid = URL(string: arrayForKey2[indexPath.row].first) 
{ 
cell.videoURL = urlValid 
} 

後您的應用程序必須工作

完整的代碼VideoPlayerView

import UIKit 
    import AVFoundation 
    import AVKit 

    class VideoPlayerView: UIView { 

    fileprivate var videoUrl : URL? 

let pauseButton: UIButton = { 
    let button = UIButton(type: .system) 
    button.setImage(#imageLiteral(resourceName: "Triangle 2"), for: .normal) 
    button.translatesAutoresizingMaskIntoConstraints = false 
    button.tintColor = UIColor.white 
    button.isHidden = false 
    button.addTarget(self, action: #selector(handlePause), for: .touchUpInside) 

    return button 
}() 

var isPlaying = false 

func handlePause() { 
    if isPlaying { 
     player?.pause() 
    pauseButton.alpha = 1.0 } 

    else { player?.play() 
     pauseButton.alpha = 0.01 
    } 

    isPlaying = !isPlaying 
} 

//container view that holds sublayers for the video control objects 
let controlsContainerView: UIView = { 
    let view = UIView() 
    view.backgroundColor = UIColor(white: 0, alpha: 1.0) 
    return view 
}() 


override init(frame: CGRect) { 
    super.init(frame: frame) 

    setupPlayerView() 

    //configures container view (video's background) 
    controlsContainerView.frame = frame 
    addSubview(controlsContainerView) 
    backgroundColor = UIColor.black 


    //following adds pause/play button to video 
    controlsContainerView.addSubview(pauseButton) 
    pauseButton.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true 
    pauseButton.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true 


} 

var player: AVPlayer? 

//function that sets up video playback 
private func setupPlayerView(url:URL) { 
    //variable that contains video url 
    self.videoUrl = url 

    player = AVPlayer(url: self.videoUrl) 

    //video only renders if you specify 'playerLayer' 
     let playerLayer = AVPlayerLayer(player: player) 
     self.layer.insertSublayer(playerLayer, at: 1) 
     playerLayer.frame = frame 


     player?.play() 


     //attached obeserver of 'player' to tell when 'player' is ready 
     player?.addObserver(self, forKeyPath: "currentItem.loadedTimeRanges", options: .new, context: nil) 

} 
//method called every time you add obserever to an object 
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { 
    //strring that lets AVPlayer know its ready 
    if keyPath == "currentItem.loadedTimeRanges" { 

     //configures container view while video is playing 
     controlsContainerView.backgroundColor = UIColor.clear 
     pauseButton.alpha = 0.05 
     isPlaying = true 

    } 
} 

required init?(coder aDecoder: NSCoder) { 
    fatalError("init(coder:) has not been implemented") 
} 
} 

全碼DrillsTableViewCell

class DrillsTableViewCell: UITableViewCell { 

var videoURL:URL? 

@IBOutlet weak var logoImage: UIImageView! 

@IBOutlet weak var drillTitle: UILabel! 


@IBOutlet weak var playButton: UIButton! 
@IBAction func watchButton(_ sender: Any) { 
    print(123) 
     guard self.videoURL != nil else{ 
      return 
     } 

     //controls video background view 
     if let keyWindow = UIApplication.shared.keyWindow { 
      let view = UIView(frame: keyWindow.frame) 
      view.backgroundColor = UIColor.white 


      view.frame = CGRect(x: 0.0, y: 0.0, width: keyWindow.frame.width, height: keyWindow.frame.height) 

      let videoPlayerFrame = CGRect(x: 0, y: 0, width: keyWindow.frame.width, height: keyWindow.frame.width * 9/16) 
      let videoPlayerView = VideoPlayerView(frame: videoPlayerFrame) 
      videoPlayerView.setupPlayerView(self.videoURL!) //added 
      view.addSubview(videoPlayerView) 


      keyWindow.addSubview(view) 
      UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseOut, animations: { 

        view.frame = keyWindow.frame 

      }, completion: { (completedAnimation) in 
       //possible features implemented later 
       UIApplication.shared.isStatusBarHidden = true 


      }) 



    } 

} 

此代碼並沒有進行測試,所以如果有一些問題讓我知道 希望這有助於

相關問題