kAiN
kAiN

Reputation: 2793

Scroll To Item UICollectionView with UIButton programmatically

I'm having a moment of confusion and I can't solve a very simple thing.

My CollectionView has 50 cells and I would like to scroll back and forth between the cells using a "Next" button and a "Back" button. I am aware of the scrollToItemAtIndexPath method but I have problems finding the right IndexPath .. Someone can help me ?

This is my Code:

// My personal method

-(void)scrollYearAtIndex:(NSInteger)index {
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    [_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}

// Show Next Items
-(void)didScrollNextYear {
    [self scrollYearAtIndex:????];
}

// Show Previous Items
-(void)didScrollPreviousYear {
    [self scrollYearAtIndex:????];
}

Upvotes: 2

Views: 908

Answers (2)

PGDev
PGDev

Reputation: 24341

I've given the answer in Swift. You can write the same logic in Objective-C.

To get the next indexPath, get the last indexPath of the sorted indexPathsForVisibleItems array and increment by 1.

To get the previous indexPath, get the first indexPath of the sorted indexPathsForVisibleItems array and decrement by 1.

func didScrollNextYear() {
    if let index = self.collectionView.indexPathsForVisibleItems.sorted().last?.row {
        let nextIndex = index+1
        if nextIndex < self.collectionView.numberOfItems(inSection: 0) {
            self.collectionView.scrollToItem(at: IndexPath(row: nextIndex, section: 0), at: .centeredHorizontally, animated: true)
        }
    }
}

func didScrollPreviousYear() {
    if let index = self.collectionView.indexPathsForVisibleItems.sorted().first?.row {
        let previousIndex = index-1
        if previousIndex >= 0 {
            self.collectionView.scrollToItem(at: IndexPath(row: previousIndex, section: 0), at: .centeredHorizontally, animated: true)
        }
    }
}

Upvotes: 4

pkc
pkc

Reputation: 8516

let indexPaths : NSArray = self.collectionView!.indexPathsForSelectedItems()
let indexPath : NSIndexPath = indexPaths[0] as NSIndexPath

This will give you current selected index path. In didScrollNextYear method, increment indexPath.row by one. And in didScrollPreviousYear, decrement indexPath.row by one.

Sample code:

// Show Next Items
-(void)didScrollNextYear {
    let indexPaths : NSArray = self.collectionView!.indexPathsForSelectedItems()
    let indexPath : NSIndexPath = indexPaths[0] as NSIndexPath

    [self scrollYearAtIndex: indexPath.row+1];
}

Upvotes: 1

Related Questions