ios - ScrollToItem 无法正常工作

标签 ios swift scroll collectionview

我有一个按钮的水平 Collection View 。单击其中一个 View Controller 时,用户将被带到另一个 View Controller 。通常,并非所有按钮都是可见的,因此我希望所选按钮位于 Collection View 的最左侧。

我试图使用scrollToItem函数来做到这一点。问题是,它每次都会将 Collection View 一直滚动到右侧。

相关代码:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return labelArray.count
}

//frees up the collection view when the scroll is active
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    isScrolling = true
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)

    //possible problem
    if isScrolling == false {
        collectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.left, animated: false)
    }

    let myLabel = cell.viewWithTag(1) as! UILabel

    let myArray = labelArray[indexPath.row]

    myLabel.text = labelArray[indexPath.row]
    myLabel.textColor = UIColor.white

    if myArray == labelArray[1] {
        cell.backgroundColor = UIColor.black
    } else {
        cell.backgroundColor = UIColor(red: 56/255, green: 120/255, blue: 195/255, alpha: 1)
    }

    return cell
}

任何帮助将不胜感激。

最佳答案

您正在 cellForItemAt 方法中调用scrollToItem 方法,该方法会为 Collection View 中的每个可见单元格调用。因此,您实际上是在尝试滚动到每个单元格变得可见。尝试在 didSelectItemAt 方法中调用scrollToItem 方法,如下所示:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
}

仅当选择单元格时才会调用 didSelectItemAt 并提供所选单元格的 IndexPath。

关于ios - ScrollToItem 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46569781/

相关文章:

ios - 重用单元格如何在 iOS 的 UITableView 中工作?

ios - RxSwift - 映射 UITableView 的 contentOffset

ios - 如何检查数组中是否已经存在自定义对象?

jquery - 如何使用 jquery 滚动窗口 onload

ios - 确定是否使用前置或后置摄像头来捕获视频

ios - 在保存到目录之前在 UIImage 中调整图像大小

ios - 403 错误 - 这是一个错误。错误 : disallowed_useragent

swift - 基于 View 的 NSTableView 中的拖放问题

CSS 滚动背景图片

javascript - 如果 body 有一个类在滚动原生 javascript 上删除