我正在尝试使用UICollectionView
构建像Instagram Stories这样的功能。我已为“集合”视图禁用了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)
}
}
}
}