cloomon
cloomon

Reputation: 25

scrollToItem does not work

I have UICollectionView and two UIButton:WeekButton and MonthButton. When I touch WeekButton or MonthButton, I want the UICollectionView to show the last element of my datasource. The difference between the function of WeekButton and MonthButton is the size of the cell of UICollectionView. When I touch either of the two button I call the scrollToItem. It worked fine when I touch MonthButton,but not when I touch WeekButton.If I touch the WeekButton twice it works.I want to know why it doesn't work when I first touch WeekButton

@IBAction func touchWeekButton(_ sender: UIButton) {
    dateProcess.isWeek=true
    dateProcess.item=historyItem
    dateCollectionView.reloadData()
    print("touchWeekButton")
    scrollToBottom()
}
@IBAction func touchMonthButton(_ sender: UIButton) {
    dateProcess.isWeek=false
    dateProcess.item=historyItem
    dateCollectionView.reloadData()
    scrollToBottom()
}

func scrollToBottom(){       
    let maxIndexPath=IndexPath(row: dateProcess.colorArray.count-1, section:0 )
    self.dateCollectionView.scrollToItem(at: maxIndexPath, at: UICollectionViewScrollPosition.bottom, animated: false)
}

extension HistoryViewController : UICollectionViewDelegateFlowLayout {

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAt indexPath: IndexPath) -> CGSize {
    if dateProcess.isWeek==true{
        let colViewHeight=collectionView.bounds.height
        let colViewWidth=collectionView.bounds.width
        let cellWidth=colViewWidth/7-1
        let cellHeight=colViewHeight/4
        return CGSize(width: cellWidth, height: cellHeight)
    }else{
        let colViewHeight=collectionView.bounds.height
        let colViewWidth=collectionView.bounds.width
        let cellWidth=colViewWidth/31
        let cellHeight=colViewHeight/16
        return CGSize(width: cellWidth, height: cellHeight)
    }

}

}

Upvotes: 1

Views: 2186

Answers (1)

Roman Podymov
Roman Podymov

Reputation: 4531

Probably you need to wait until your collectionView will be reload and only after that you can scroll to any item. You can do it like that:

@IBAction func touchWeekButton(_ sender: UIButton) {
    dateProcess.isWeek=true
    dateProcess.item=historyItem
    dateCollectionView.reloadData()
    print("touchWeekButton")
    DispatchQueue.main.async {

        scrollToBottom()            
    }
}
@IBAction func touchMonthButton(_ sender: UIButton) {
    dateProcess.isWeek=false
    dateProcess.item=historyItem
    dateCollectionView.reloadData()
    DispatchQueue.main.async {

        scrollToBottom()            
    }
}

Upvotes: 5

Related Questions