From 3066c1bfbc4581e64a0fc2b97b06b2595f8e0ffc Mon Sep 17 00:00:00 2001 From: Alberto Aldegheri Date: Mon, 14 Apr 2025 18:54:23 +0200 Subject: [PATCH] Fix carousel initial position bug --- .../Items2/iOS/CarouselViewController2.cs | 47 +++++++++---------- 1 file changed, 21 insertions(+), 26 deletions(-) diff --git a/src/Controls/src/Core/Handlers/Items2/iOS/CarouselViewController2.cs b/src/Controls/src/Core/Handlers/Items2/iOS/CarouselViewController2.cs index ece28de99c98..958e155fa54a 100644 --- a/src/Controls/src/Core/Handlers/Items2/iOS/CarouselViewController2.cs +++ b/src/Controls/src/Core/Handlers/Items2/iOS/CarouselViewController2.cs @@ -509,30 +509,7 @@ async Task UpdateInitialPosition() return; } - int position = carousel.Position; - var currentItem = carousel.CurrentItem; - - if (currentItem != null) - { - // Sometimes the item could be just being removed while we navigate back to the CarouselView - var positionCurrentItem = ItemsSource.GetIndexForItem(currentItem).Row; - if (positionCurrentItem != -1) - { - position = positionCurrentItem; - } - } - - var projectedPosition = NSIndexPath.FromItemSection(position, _section); - - if (LoopItemsSource.Loop) - { - //We need to set the position to the correct position since we added 1 item at the beginning - projectedPosition = GetScrollToIndexPath(position); - } - - var uICollectionViewScrollPosition = IsHorizontal ? UICollectionViewScrollPosition.CenteredHorizontally : UICollectionViewScrollPosition.CenteredVertically; - - await Task.Delay(100).ContinueWith((t) => + await Task.Delay(100).ContinueWith(_ => { MainThread.BeginInvokeOnMainThread(() => { @@ -540,6 +517,7 @@ await Task.Delay(100).ContinueWith((t) => { return; } + InitialPositionSet = true; if (ItemsSource is null || ItemsSource.ItemCount == 0) @@ -547,6 +525,25 @@ await Task.Delay(100).ContinueWith((t) => return; } + int position = carousel.Position; + var currentItem = carousel.CurrentItem; + + if (currentItem != null) + { + // Sometimes the item could be just being removed while we navigate back to the CarouselView + var positionCurrentItem = ItemsSource.GetIndexForItem(currentItem).Row; + if (positionCurrentItem != -1) + { + position = positionCurrentItem; + } + } + + var projectedPosition = LoopItemsSource.Loop + ? GetScrollToIndexPath(position) // We need to set the position to the correct position since we added 1 item at the beginning + : NSIndexPath.FromItemSection(position, _section); + + var uICollectionViewScrollPosition = IsHorizontal ? UICollectionViewScrollPosition.CenteredHorizontally : UICollectionViewScrollPosition.CenteredVertically; + CollectionView.ScrollToItem(projectedPosition, uICollectionViewScrollPosition, false); //Set the position on VirtualView to update the CurrentItem also @@ -554,9 +551,7 @@ await Task.Delay(100).ContinueWith((t) => UpdateVisualStates(); }); - }); - } void UpdateVisualStates()