ios - UICollectionView 自动滚动跳过一个项目
问题描述
我正在尝试使用UICollectionView
. 我为 Collection 视图禁用了 UserInteraction,但是在使用 时collectionView.scrollToItem
,CollectionView 会跳过一个单元格。这是我的代码。这可能是什么问题?
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let screenSize = UIScreen.main.bounds.size
return screenSize
}
private var playbackLikelyToKeepUpContext = 0
private var currentIndexPath: IndexPath?
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "storiesCell", for: indexPath) as? StoriesCell {
let currentContent = allVideoUrls[indexPath.item]
currentIndexPath = indexPath
Logger.print(currentIndexPath!.item)
if let url = URL(string: currentContent) {
let playerItem:AVPlayerItem = AVPlayerItem(url: url)
player = AVPlayer(playerItem: playerItem)
let playerLayer=AVPlayerLayer(player: player!)
playerLayer.frame=CGRect(x:0, y:0, width:self.view.bounds.width, height:self.view.bounds.height)
cell.layer.addSublayer(playerLayer)
self.view.layer.addSublayer(playerLayer)
storiesCollectionView.isScrollEnabled = false
player!.addObserver(self, forKeyPath: "currentItem.playbackLikelyToKeepUp",
options: .new, context: &playbackLikelyToKeepUpContext)
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil) // Add observer
return cell
}
}
return UICollectionViewCell()
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == &playbackLikelyToKeepUpContext && player != nil{
Logger.print(currentIndexPath)
if player!.currentItem != nil {
if player!.currentItem!.isPlaybackLikelyToKeepUp {
player!.play()
// loadingIndicatorView.stopAnimating() or something else
} else {
// loadingIndicatorView.startAnimating() or something else
}
}
}
}
@objc func playerItemDidReachEnd(notification: NSNotification) {
if currentIndexPath != nil {
let currentRow = currentIndexPath!.item
let nextItem = currentIndexPath!.item + 1
player = nil
if currentRow < allVideoUrls.count {
Logger.print("Next: \(nextItem)")
let nextIndexPath = IndexPath(item: nextItem, section: 0)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
self.storiesCollectionView.scrollToItem(at: nextIndexPath, at: [.centeredVertically, .centeredHorizontally], animated: true)
}
}
}
}
解决方案
推荐阅读
- c# - 使用表列和行 C# 反序列化 JSON
- r - 为什么我的函数不工作,即使函数内的循环是
- css - 是否可以使用 css3 变量作为 SASS mixin 的参数?
- regex - 有没有办法在不使用 REGEX 的情况下从 VBA 中查找和替换 .txt 或 .xml 文件?
- java - 如何使用 java 创建自定义目录
- c++ - 读取磁力计数据 MPU9250 AK8963
- asp.net-core-mvc - saveChangesAsync 更新对象我没有保存
- python - 如何正确使用 Python 列表推导?
- android - 关闭活动时如何从 Recyclerview 停止 Exoplayer?
- c# - Ef 核心负载树列表