我正在尝试播放屏幕上最可见的单元的视频。我使用的是视频单元使用的协议,称为VideoProtocol
:
protocol VideoProtocol : class {
func toggleVideo(shouldPlay: Bool, cellIsVisible: Bool?)
}
这使我可以在单元格中开始和停止视频。
然后我遍历所有可见单元格,记录可见百分比最高的单元格,然后播放该单元格。然后,我遍历所有其他单元,并告诉它们停止播放。这是我的代码:
func playVisibleVideoCells() {
var videoCell: (UICollectionViewCell & VideoProtocol)?
var greatestPercentage: CGFloat = 0
for cell in collectionView.visibleCells {
if let cell = cell as? (UICollectionViewCell & VideoProtocol) {
let percentageVisible = cell.frame.intersection(collectionView.bounds).size.height / cell.frame.height
if percentageVisible > greatestPercentage {
videoCell = cell
greatestPercentage = percentageVisible
}
}
}
if let cell = videoCell {
if greatestPercentage > 0.3 {
cell.toggleVideo(shouldPlay: true, cellIsVisible: true)
} else {
cell.toggleVideo(shouldPlay: false, cellIsVisible: false)
}
for cell in collectionView.visibleCells {
if let cell = cell as? (UICollectionViewCell & VideoProtocol) {
if cell === videoCell {
continue
} else {
cell.toggleVideo(shouldPlay: false, cellIsVisible: false)
}
}
}
}
}
每次在scrollViewDidScroll
上都会调用它。有没有更紧凑的方法来实现这一目标?有什么方法可以改进我的代码以加快速度吗?谢谢!