【问题标题】:collectionView doesn't scrollToItem - swift - programmaticallycollectionView 不会 scrollToItem - swift - 以编程方式
【发布时间】:2021-01-28 01:20:52
【问题描述】:

我以这种方式在 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.

【问题讨论】:

    标签: swift uicollectionview collectionview indexpath


    【解决方案1】:

    我觉得像

    IndexPath(item: 0, section: counter)
    

    向后(两次)。试试

    IndexPath(item: counter, section: 0)
    

    在这两个地方。

    【讨论】:

    • 它没有像以前那样给我警告,但它还没有滚动到该索引路径的项目,我还注意到 collectionView 的 contentSize 是 (355.0, 1667.0) 这意味着它是垂直开发的,而不是我想要的水平开发
    • 当然,我也想过,但那是另一回事。说这是水平还是垂直滚动的集合视图取决于您。您没有在配置videoCollectionView 的位置显示任何代码,所以我没有理由相信您这样做是正确的。
    • 我通过添加自定义 UICollectionViewFlowLayout() 并将其 scrollDirection 属性设置为水平解决了这个问题
    • 是的,我不确定您所说的“自定义”是什么意思; UICollectionViewFlowLayout scrollDirection 属性,你可以设置它。您不需要为此目的进行子类化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 2017-12-28
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多