swift - collectionView 不 scrollToItem - swift - 以编程方式
问题描述
我以这种方式在 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)
在这两个地方。
推荐阅读
- asp.net - VB .Net:Json 不使用 ASHX 返回
- python-3.x - 使用 NLTK 将命令链接到聊天
- bash - Sed 将下划线字符串转换为 CamelCase 在数字上失败
- microsoft-teams - 无法通过 Microsoft 团队消息卡中的“HttpPOST”操作发布到目标 URL
- ios - NSSecureCoding 在简单地创建 SCNNode 时抛出
- node.js - Angular 8中子组件与父组件之间的通信
- azure-devops - BizTalk 部署 2016 通过管道
- mysql - 如何让 ASP.NET 角色使用 MySQL?
- beautifulsoup - 标签包含句号时如何导航汤数据结构
- hive - Pyspark:将数据帧插入分区配置单元表