Skip to content

Commit 27d82a7

Browse files
committed
fix(ios): prevent crash on scrollToIndex
if index is out of bounds
1 parent 921619e commit 27d82a7

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

src/collectionview/index.ios.ts

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -701,13 +701,20 @@ export class CollectionView extends CollectionViewBase {
701701
return this.nativeViewProtected?.contentOffset.y || 0;
702702
}
703703
public scrollToIndex(index: number, animated: boolean = true, snap: SnapPosition = SnapPosition.START) {
704-
let scrollPosition = UICollectionViewScrollPosition.Top;
705-
if (this.orientation === 'vertical') {
706-
scrollPosition = snap === SnapPosition.START ? UICollectionViewScrollPosition.Top : UICollectionViewScrollPosition.Bottom;
707-
} else {
708-
scrollPosition = snap === SnapPosition.START ? UICollectionViewScrollPosition.Left : UICollectionViewScrollPosition.Right;
704+
const nativeView = this.nativeViewProtected;
705+
if (!nativeView) {
706+
return;
707+
}
708+
const nbItems = nativeView.numberOfItemsInSection(0);
709+
if(nbItems > 0 && index < nbItems) {
710+
let scrollPosition = UICollectionViewScrollPosition.Top;
711+
if (this.orientation === 'vertical') {
712+
scrollPosition = snap === SnapPosition.START ? UICollectionViewScrollPosition.Top : UICollectionViewScrollPosition.Bottom;
713+
} else {
714+
scrollPosition = snap === SnapPosition.START ? UICollectionViewScrollPosition.Left : UICollectionViewScrollPosition.Right;
715+
}
716+
nativeView.scrollToItemAtIndexPathAtScrollPositionAnimated(NSIndexPath.indexPathForItemInSection(index, 0), scrollPosition, animated);
709717
}
710-
this.nativeViewProtected.scrollToItemAtIndexPathAtScrollPositionAnimated(NSIndexPath.indexPathForItemInSection(index, 0), scrollPosition, animated);
711718
}
712719

713720
scrollToOffset(value, animated) {

0 commit comments

Comments
 (0)