繁体   English   中英

ScrollToItem无法正常工作

[英]ScrollToItem isn't working properly

我有一个按钮的水平收集视图。 单击其中一个时,用户将被带到另一个视图控制器。 通常,并非所有按钮都可见,所以我希望所选按钮位于集合视图的最左侧。

我试图用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
}

任何帮助将不胜感激。

您正在cellForItemAt方法中调用scrollToItem方法,对于集合视图中的每个可见单元格都会调用该方法。 因此,您实质上是在尝试滚动到每个可见的单元格。 尝试像这样在didSelectItemAt方法中调用scrollToItem方法:

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

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

我知道了。 我所做的就是改变

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)
}

以前,它会滚动到每个单元,而不会停在每个单元上。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM