【发布时间】:2020-12-02 13:48:26
【问题描述】:
我已经为一个问题苦苦挣扎了很多天。我正在使用嵌套结构来显示多张照片和视频,例如 Instagram 提要。但问题是,当我启动 viewController 时,它开始播放视频并且在滚动时不会停止播放视频。如何仅播放嵌套结构中可见单元格的视频并停止所有其他视频?
在这里简单解释一下我的结构, UIViewController -> UITableView -> UITableViewCell -> UICollectioinView -> UICollectionViewCell -> section = 0(对于照片数组)+ section = 1(对于多个视频)。
extension HomeVC: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
postsArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTVC", for: indexPath) as! HomeTVC
let objPost = postsArray[indexPath.row]
cell.postImagesArray = []
cell.postImagesArray = objPost.images ?? [Images].init()
cell.videos = []
cell.videos = objPost.videos ?? []
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let tableViewCell = cell as? HomeTVC else { return }
tableViewCell.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, forRow: indexPath.row)
}
}
UICollectionView 委托方法
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCVC", for: indexPath) as! HomeCVC
if indexPath.section == 0 {
let images = postsArray[collectionView.tag].images?[indexPath.row]
let imagePath = APIConstants.BasePathImage + (images?.post_merge_image ?? "")
cell.imgPropertyView.sd_setImage(with: URL(string: imagePath), placeholderImage: UIImage(named: "placeholder"))
return cell
} else {
let videos = postsArray[collectionView.tag].videos?[indexPath.row]
cell.videoView.isHidden = false
let videoUrl = APIConstants.BasePathImage + (videos?.post_video ?? "")
cell.playVideo(videoUrl)
return cell
}
}
func collectionView(_ collectionView: UICollectionView,
didEndDisplaying cell:
UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let cell = cell as? HomeCVC else {return}
cell.stopVideo()
}
【问题讨论】:
-
为什么你的
didEndDisplaying方法在cellForItemAt里面? -
您能帮我解决问题吗?
-
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath)在UICollectionViewDelegate中定义,因此您应该确保将委托以及数据源设置为您的tableViewCell,例如collectionView.dataSource = self和collectionView.delegate = self,在这样做之后didEndDisplaying你的 tableViewCell 中的方法将被调用,你的逻辑应该工作
标签: swift uitableview video uicollectionview