【问题标题】:ScrollToItem isn't working properlyScrollToItem 无法正常工作
【发布时间】:2017-10-04 16:27:12
【问题描述】:

我有一个水平的按钮集合视图。当其中一个被点击时,用户被带到另一个视图控制器。很多时候并不是所有的按钮都是可见的,所以我想要的是让选定的按钮位于集合视图的最左侧。

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

相关代码:

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
}

任何帮助将不胜感激。

【问题讨论】:

    标签: ios swift scroll collectionview


    【解决方案1】:

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

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

    didSelectItemAt 仅在选定单元格时调用,并提供选定单元格的 IndexPath。

    【讨论】:

    • 所以我确实尝试在 didSelectItemAt 方法中实现这个。它确实阻止集合视图在开始时滚动到右侧,问题是它没有对它做任何事情。
    • 我测试了上面的代码,见编辑,在我构建的一个简单的集合视图应用程序中工作。在没有看到您如何实现 didSelectItemAt 方法或类中的其余代码的情况下,我不确定您的问题出在哪里。
    • 我让它在 cellForItemAt 方法中工作。只需对项目索引进行硬编码。我会发布答案。感谢您的帮助。
    • 如何对项目索引进行硬编码?该索引将基于用户选择的项目。
    • 我的意思是 indexPath。
    【解决方案2】:

    我让它工作了。我所做的只是改变

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

    if isScrolling == false {
        let i = IndexPath(item: 1, section: 0)
        collectionView.scrollToItem(at: i, at: .right, animated: false)
    }
    

    以前它会滚动到每个单元格,而不会在每个单独的单元格处停止。

    因此,对于每个项目,我都会根据所选部分对值进行硬编码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-31
      • 2016-12-01
      • 1970-01-01
      • 2016-09-01
      • 2012-07-11
      • 2018-04-08
      • 2017-04-20
      • 2018-10-02
      相关资源
      最近更新 更多