Reputation: 592
I have a button connected from storyboard that I want to scroll my horizontally scrolling collection view one item to the right when pressed. Here is the code I came up with:
- (IBAction)rightButton:(id)sender {
NSIndexPath *indexPath = [self.collectionView indexPathsForSelectedItems];
NSIndexPath* newIndexPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:indexPath.section];
[self.collectionView scrollToItemAtIndexPath:newIndexPath
atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
animated:YES];
}
However, this is creating a crash, with the error
-[__NSArrayI row]: unrecognized selector sent to instance 0x178232540
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI row]: unrecognized selector sent to instance 0x178232540'
I suspect the problem is that this code is more for a TableView and it doesn't like the section park in there.
Can someone help me out with this and figure out why I get an error? Is there a better way to do this?
Thanks
Upvotes: 0
Views: 2348
Reputation: 34839
The indexPathsForSelectedItems
method name has an extra s
in it, Paths
not Path
, which indicates that it returns an NSArray
of index paths, not a single index path. Hence the solution is to change these lines
NSIndexPath *indexPath = [self.collectionView indexPathsForSelectedItems];
NSIndexPath* newIndexPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:indexPath.section];
to this
NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
NSArray *indexPaths = [self.collectionView indexPathsForSelectedItems];
if ( indexPaths.count > 0 )
{
NSIndexPath *oldIndexPath = indexPaths[0];
NSInteger oldRow = oldIndexPath.row;
newIndexPath = [NSIndexPath indexPathForRow:oldRow + 1 inSection:oldIndexPath.section];
}
Upvotes: 1