UICollectionView - scroll to the next page

2019-05-07 03:59发布

问题:

Is there any chance to scroll in the UICollectionView to the wanted item using . scrollToItemAtIndexPath and snap not to the item itself, but to the page the item is part of? (I got paging enabled.)

Cheers

回答1:

You need to create NSIndexPath than scroll to that index.

 //Mark: - Move to cell when view did appear

overload viewDidAppear() {


    let scrollIndex: NSIndexPath = NSIndexPath(forItem: dayIndex, inSection: monthSection)
    if (// Check you are in range of UIcollectionView's count) {
        //Scroll collectionview according to your requirement i.e UICollectionViewScrollPositionCenteredHorizontally or UICollectionViewScrollPosition.Left 
        self.YourCollectionView.scrollToItemAtIndexPath(scrollIndex, atScrollPosition: UICollectionViewScrollPositionCenteredHorizontally, animated: true)
    }
}


回答2:

I did end up using offsetContent property;

I knew the width of every so called page.

  1. I wrote a code to get the indexPath for current day
  2. I retrieved the section of the indexPath
  3. I multiplied the section by the width of the view and named it "offset"
  4. I set my UICollectionView.contentOffset.x to "offset" and it works fine.

I also tried using .scrollRectToVisible and the offset, and it worked amazingly, but I also wanted to updated something that was based on the contentOffset of the UICollectionView, and the .scrollRectToVisible seems not to update this property - it was updated only after I dragged the view a little.

Thanks for all your help!