我在UIView中设置了一个UICollectionview,方法如下:
videoCollectionView.delegate = self
videoCollectionView.dataSource = self
self.playerView.insertSubview(videoCollectionView, belowSubview: additionalItemsView)
videoCollectionView.fillSuperview()
数据源和委托方法就是这样实现的
extension CardView : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let numberOfURLS = cardModel?.urlStrings?.count
return numberOfURLS!
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let videoCell = collectionView.dequeueReusableCell(withReuseIdentifier: "videoCellIdentifier", for: indexPath)
videoCell.backgroundColor = UIColor.random()
return videoCell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.bounds.width, height: self.bounds.height)
}
}
从上面的代码中可以看出,每个单元格都是collectionView.frame
的大小我想让collectionView单元格水平显示,并能够在其中滚动。
这是我实现的在单元格中水平滚动的代码:
fileprivate func goToNextVideo(){
counter = counter+1
counter = min(cardModel!.urlStrings!.count-1, counter)
videoCollectionView.scrollToItem(at: IndexPath(item: 0, section: counter), at: .left, animated: true)
}
fileprivate func goToPreviousVideo(){
counter = counter - 1
counter = max(0, counter)
videoCollectionView.scrollToItem(at: IndexPath(item: 0, section: counter), at: .left, animated: true)
}
我不知道是什么原因,collectionView没有滚动到所需的单元格,我在控制台中收到了这个警告:
Warning: Invalid IndexPath <NSIndexPath: 0xa5dbc31284d24cfa> {length = 2, path = 1 - 0} specified - will use a contentOffset of {0,0} as a fallback value.
在我看来像
IndexPath(item: 0, section: counter)
向后(两次(。尝试
IndexPath(item: counter, section: 0)
在这两个地方。