簡體   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