我有一个从数据库中获取数据的 tableView。我的 TableView 中的一些单元格中包含视频,当我们遇到视频时,它会正确显示。
我的问题是,如果有人继续滚动,那么该视频仍会继续播放。我想改变它,如果用户观看了视频的一部分然后继续滚动,那么我想在那里结束视频。我想我快要解决这个问题了,但还没有完全解决。
这是我的代码:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Home", for: indexPath) as! Home
let filename = streamsModel.video_image[indexPath.row] as NSString
if filename.pathExtension == "mov" {
let movieURL = URL(string: streamsModel.video_image[indexPath.row])
cell.videoCapHeight.constant = CGFloat(Float(cell.pic_height!))
cell.playerView = AVPlayer(url: movieURL!)
cell.MyAVPlayer.player = cell.playerView
cell.MyAVPlayer.showsPlaybackControls = false
cell.MyAVPlayer.view.frame = cell.videoView.bounds
cell.videoView.addSubview(cell.MyAVPlayer.view)
controller.addChildViewController(cell.MyAVPlayer)
cell.playerView?.isMuted = false
cell.MyAVPlayer.player?.play()
}
return cell
}
上面的代码只是检查 streamsModel.video_image
是否有 .mov 扩展名 (JSON)。如果是,则获取电影/视频并将其显示在 AVPlayer 中。
从代码中可以看出,使用了 Play()
方法,因此视频会自动开始播放。问题是,例如,如果一段视频时长为 1 分钟,你观看了 20 秒,然后向下滚动,你仍然会听到该视频正在播放,我想在用户滚动离开时立即停止视频。
这是我的 scrollView 代码,现在我只需要在此处滚动或在 UITableViewCell 中停止视频:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (self.lastContentOffset > scrollView.contentOffset.y + 0) {
print("scrolling up")
}
else if (self.lastContentOffset < scrollView.contentOffset.y) {
print("scrolling down")
}
self.lastContentOffset = scrollView.contentOffset.y
}
最佳答案
Dan 关于使用 TableView 的委托(delegate)方法的建议在这里很适合您,这意味着您可以在单元格移出屏幕时暂停视频。
像这样的东西应该可以工作:
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// Dequeue the cell
let cell = tableView.dequeueReusableCell(withIdentifier: "Home", for: indexPath) as! Home
// Check the player object is set (unwrap it)
if let player = cell.MyAVPlayer.player {
// Check if the player is playing
if player.rate != 0 {
// Pause the player
player.pause()
}
}
}
我建议自动暂停和再次播放可能会有点滞后,具体取决于是否有缓冲等...因此您可能需要考虑允许用户点击播放视频。
关于ios - 用户滚动时如何停止视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46549113/