如何让按钮根据按下的行显示不同的视频?
Posted
技术标签:
【中文标题】如何让按钮根据按下的行显示不同的视频?【英文标题】:How to get button to display different video according to the row it is pressed in? 【发布时间】:2017-08-13 07:22:43 【问题描述】:目前,我将代码设置为每个表格视图单元格中的某个位置,该按钮在按下后显示视频。每个表格视图单元格行都包含按钮(有 x 个单元格),但是无论在哪一行点击按钮,它总是会导致相同的视频。有没有办法根据按钮所在的行来显示视频?我的代码目前只有一个视频文件,但我如何才能根据点击按钮的单元格将其显示到特定视频的位置?例如,如果在第一行中点击按钮,我希望它显示某个视频,第二个和三个相同,依此类推。现在它们都显示相同的视频。
这是我的表格视图单元格代码:
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 player: AVPlayer?
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
()
required init?(coder aDecoder: NSCoder)
fatalError("init(coder:) has not been implemented")
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
//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
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
)
表格视图代码:
class DrillsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
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
cell.playButton.tag = indexPath.row
//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
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]
【问题讨论】:
如果您不显示相关的表格视图代码和您的按钮处理代码,任何人都无法提供帮助。 这是UIView
的代码,而不是UITableViewCell
我添加了认可代码
你说的按钮是playButton?
是的,没错
【参考方案1】:
我认为您应该重构代码以获得所需的行为。请检查以下代码:
首先对名为setupPlayerView
的VideoPlayerView
方法进行更改。将您的实现替换为:
func setupPlayerView(for url: URL)
player = AVPlayer(url: url)
//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)
现在更改DrillsTableViewCell
,更改videoURLs,我添加了一个新变量singleVideoURL,你的新类将如下所示:
class DrillsTableViewCell: UITableViewCell
var videoURLs:[URL] = [URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BlackHeartBB/dunk.mov"), URL(fileURLWithPath: "/Users/jordanlagrone/Desktop/BlackHeartBB/BlackHeartBB/mk.MOV")]
@IBOutlet weak var logoImage: UIImageView!
@IBOutlet weak var drillTitle: UILabel!
@IBOutlet weak var playButton: UIButton!
@IBAction func watchButton(_ sender: UIButton)
print(123)
//controls video background view
if let keyWindow = UIApplication.shared.keyWindow
let view = UIView(frame: keyWindow.frame)
view.backgroundColor = UIColor.white
var singleVideoURL = videoURLs[sender.tag]
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(for: singleVideoURL)
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
)
【讨论】:
这段代码没有完成我想要做的事情。这很简单。如果在第 1 行点击按钮,我希望播放特定视频,第 2 行和第 3 行等相同。按钮应该知道它被按下的行,并取决于它在特定视频中的行(与该行相关联) 应该播放。 @CaptainCode 上面的代码将从 videoURLs 数组中选择 url,例如单击第 0 行中的按钮,在您的表格视图中,您将 indexPath.row 提供给 button.tag,因此它将为 0,并且当它进入 action 方法时,它会从 videoURLs 中选择索引为 0 的视频 url 并播放它,这不是你想要的吗?如有错误请指正 是的,这就是我想要完成的。 @CaptainCode 你试过上面的代码吗?我想它也在做同样的事情,请检查 @CaptainCode 你能告诉我上面代码中的错误是什么吗?【参考方案2】:首先,您必须通过在 tableView:cellForRowAtIndexPath: 方法中赋予它们标签值来区分单元格中添加的按钮
cell.button.tag = indexpath.row
这将为每个单元格中的按钮设置不同的标记值。 然后添加以下内容:
cell.button.addTarget(self, action:(YourController.buttonMethodPlayVideo(:)) , forControlEvents: .TouchUpInside)
为按钮创建一个方法以在点击时执行操作:
func buttonMethodPlayVideo(sender: UIButton)
print(sender.tag)
在上述方法中,当您单击按钮时,您将获得不同的标签值。 根据该值,您可以播放不同的视频或将不同的视频名称传递给播放器以播放视频。
【讨论】:
谢谢,还没有实现代码,但是这很清楚,似乎适用!现在试试... 我添加了更多代码来帮助更好地解释我的问题。这会改变我的问题的解决方案吗? 我应该将buttonMethodPlayVideo
方法放在我的代码中的什么位置?
在表格视图控制器或您添加了表格视图的视图控制器中【参考方案3】:
设置一个数组以将视频的路径放入其中,其索引应与单元格的索引匹配。此外,您可以将单元格的行号作为其标签传递给里面的按钮。所以当你点击那个按钮时,你可以通过按钮的标签在数组中找到特定的视频路径。
【讨论】:
以上是关于如何让按钮根据按下的行显示不同的视频?的主要内容,如果未能解决你的问题,请参考以下文章