Skip to content

[iOS/MacCatalyst] Fixed CollectionView: Preserve visible position when item spacing changes - #37032

Merged
kubaflo merged 8 commits into
dotnet:inflight/currentfrom
KarthikRajaKalaimani:fix-36422
Oct 20, 2026
Merged

kubaflo merged 8 commits into
dotnet:inflight/currentfrom
KarthikRajaKalaimani:fix-36422

Conversation

@KarthikRajaKalaimani

@KarthikRajaKalaimani KarthikRajaKalaimani commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Note

Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!

Issue Details

On iOS/MacCatalyst, increasing CollectionView.ItemSpacingat runtime silently shifts ContentOffset, hiding the first item until the user manually scrolls up.

Root Cause

  • File: src/Controls/src/Core/Handlers/Items2/iOS/ItemsViewController2.cs
  • Any spacing/span change routes: CollectionViewHandler2.OnItemsLayoutPropertyChanged → UpdateLayout() → ItemsViewController2.UpdateLayout(newLayout) → EnsureLayoutInitialized()
  • EnsureLayoutInitialized() always builds and swaps in a brand-new UICollectionViewCompositionalLayout instance via CollectionView.SetCollectionViewLayout(ItemsViewLayout, false).
  • Because CollectionView items use self-sizing/estimated dimensions (NSCollectionLayoutDimension.CreateEstimated(30f)), UIKit's self-sizing reconciliation — triggered because the fresh layout instance has no prior size cache — synchronously shifts ContentOffset as a side effect of that single call.
  • Confirmed via logging: ContentOffset.Y moved 0 → 22.5 → 42.5 → 142.5 as spacing increased 20 → 50 → 100 → 150, with all drift happening inside the SetCollectionViewLayout call (no further drift afterward).

Description of Change

  • Captures the offset before the layout swap, restores it if UIKit shifted it.
  • ResetScrollTracking() prevents a spurious Scrolled delta from being computed against the transient drifted value — this exact pattern (ResetScrollTracking() + ContentOffset assignment) already exists elsewhere in the same file (UpdateItemsSource()), so the fix matches established codebase convention.
  • Verified: scrolled-away-from-top positions are correctly preserved (not force-reset to zero) — no regression.

Issues Fixed

Fixes
#36422
#34785

Tested the behavior in the following platforms.

  • Android
  • Windows
  • iOS
  • Mac
Before After
Before_36422.mov
After_36422.mov

@github-actions

github-actions Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 37032

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 37032"

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service dotnet-policy-service Bot added the community ✨ Community Contribution label Aug 3, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Hey there @@KarthikRajaKalaimani! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@dotnet-policy-service dotnet-policy-service Bot added the partner/syncfusion Issues / PR's with Syncfusion collaboration label Aug 3, 2026
@vishnumenon2684

Copy link
Copy Markdown
Contributor

/azp run maui-pr-uitests , maui-pr-devicetests

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 2 pipeline(s).

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Aug 3, 2026
@MauiBot MauiBot added s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-gate-failed AI could not verify tests catch the bug s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) labels Aug 3, 2026
@MauiBot

This comment has been minimized.

@MauiBot MauiBot removed the s/agent-review-in-progress AI review is currently running for this PR label Aug 3, 2026
kubaflo pushed a commit that referenced this pull request Aug 3, 2026
A VerifyScreenshot failure 'Snapshot different than baseline: X.png (size
differs - baseline is WxH pixels, actual is WxH pixels)' means the committed
baseline PNG has different DIMENSIONS than the gate simulator's screenshot —
the baseline was captured on a different-sized device than the gate boots
(e.g. an iPhone 16 Pro 1206x2472 baseline vs the pinned iPhone 11 Pro
1124x2286). A PR *code* fix can never change screenshot dimensions, so the
same mismatch appears in BOTH the without-fix and with-fix runs and the gate
cannot A/B verify the test — it must report INCONCLUSIVE, never FAILED.

The existing guards only covered 'Baseline snapshot not yet created' and
'N% difference' residuals; a size mismatch has no percentage, so it fell
through to a genuine FAILED (build 14850018, PR #37032 iOS Issue36422).

Classify it as env/INCONCLUSIVE in both Get-TestResultFromOutput paths (the
device-test Passed:/Failed: count path and the UITest NUnit fall-through),
guarded so it only fires when every remaining failure is a size mismatch
(or size + new-baseline) — a real 'N% difference' pixel diff against a
same-size baseline is still counted as a genuine visual regression. +3 Pester
tests (37 pass).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 15d2af20-e4ab-4e88-9011-cfbd83513bc0
@kubaflo

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

Note

🔍 /review started

AzDO build 15511217 is running for ios.

The s/agent-review-in-progress label stays on this PR while the run is active. The final recommendation and outcome labels are posted only after Gate, expert review, and Deep UI tests finish.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Expert Review — 1 findings

See inline comments for details.

public override string Issue => "Changing ItemSpacing at runtime shifts CollectionView's ContentOffset, hiding the first item";

[Test]
[Category(UITestCategories.CollectionView)]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 AI-Generated Review (multi-model)

[major] Regression Prevention and Test Coverage — The new CollectionView UI test uses [Category(UITestCategories.CollectionView)] instead of method-level [ShardedTestCategory(UITestCategories.CollectionView, shard: ...)]. Concrete failure: analyzer MAUI0003 blocks Controls.TestCases.iOS.Tests compilation, so the regression test cannot execute and the PR cannot be validated.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review Summary

@KarthikRajaKalaimani — new AI review results are available based on commit 0b18c80.

Gate Failed Confidence Low Platform iOS


🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix

Gate Result: ❌ FAILED

Platform: IOS · Base: main · Merge base: de3cf139

🩺 The PR's test does not compile — the build error is in one of the PR's own test files, which the gate never reverts, so it fails identically without and with the fix. This is NOT a pre-existing/environment failure — the PR must fix its test (e.g. an ambiguous using / type collision). Investigate the PR's test code.

/Users/cloudtest/vss/_work/1/s/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue36422.cs(18,15): error MAUI0003: Test method 'ChangingItemSpacingDoesNotShiftFirstItemOutOfView' uses the sha...

Test Without Fix (expect FAIL) With Fix (expect PASS)
🖥️ Issue36422 Issue36422 🛠️ BUILD ERROR 🛠️ BUILD ERROR
🔴 Without fix — 🖥️ Issue36422: 🛠️ BUILD ERROR · 249s

Error-relevant lines (filtered from the build log):

/Users/cloudtest/vss/_work/1/s/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue36422.cs(18,15): error MAUI0003: Test method 'ChangingItemSpacingDoesNotShiftFirstItemOutOfView' uses the sharded category 'CollectionView' directly; use `[ShardedTestCategory(UITestCategories.CollectionView, shard: ...)]` so both the umbrella and CI shard categories are registered [/Users/cloudtest/vss/_work/1/s/src/Controls/tests/TestCases.iOS.Tests/Controls.TestCases.iOS.Tests.csproj]
🟢 With fix — 🖥️ Issue36422: 🛠️ BUILD ERROR · 92s

Error-relevant lines (filtered from the build log):

/Users/cloudtest/vss/_work/1/s/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue36422.cs(18,15): error MAUI0003: Test method 'ChangingItemSpacingDoesNotShiftFirstItemOutOfView' uses the sharded category 'CollectionView' directly; use `[ShardedTestCategory(UITestCategories.CollectionView, shard: ...)]` so both the umbrella and CI shard categories are registered [/Users/cloudtest/vss/_work/1/s/src/Controls/tests/TestCases.iOS.Tests/Controls.TestCases.iOS.Tests.csproj]

⚠️ Failure Details

  • 🛠️ Issue36422 without fix: build failed before tests could run
    • /Users/cloudtest/vss/_work/1/s/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue36422.cs(18,15): error MAUI0003: Test method 'ChangingItemSpacingDoesNotShiftFirstItemOutOfView' uses the sha...
  • 🛠️ Issue36422 with fix: build failed (fix does not compile)
    • /Users/cloudtest/vss/_work/1/s/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue36422.cs(18,15): error MAUI0003: Test method 'ChangingItemSpacingDoesNotShiftFirstItemOutOfView' uses the sha...
📁 Fix files reverted (1 files)
  • src/Controls/src/Core/Handlers/Items2/iOS/ItemsViewController2.cs

📋 Pre-Flight — Context & Validation

PR #37032 Pre-Flight

Context

  • PR: [iOS/MacCatalyst] Fixed CollectionView: Preserve visible position when item spacing changes
  • Issue: #36422, “I2-After changing the vertical spacing, need to scroll up to make the first item visible.”
  • Target platform for STEP 5a: iOS
  • Base / review branch: main / local materialized branch pr-review-37032
  • Materialized review commit: a5b6a2c6ac66c21d0bc9b76f69fd0a668c1b2a7d
  • Merge base used by the completed gate: de3cf139

The issue reproduces when a vertical CollectionView is at the origin and ItemSpacing changes at runtime. The Items2 property-change path rebuilds the compositional layout:

CollectionViewHandler2.OnItemsLayoutPropertyChanged → UpdateLayout() → ItemsViewController2.UpdateLayout(newLayout) → EnsureLayoutInitialized() → UICollectionView.SetCollectionViewLayout(...)

UIKit's estimated/self-sizing reconciliation can move ContentOffset.Y, hiding the first item until the user scrolls upward.

Existing PR Approach

The production change is limited to:

src/Controls/src/Core/Handlers/Items2/iOS/ItemsViewController2.cs

Immediately around SetCollectionViewLayout, the PR captures CollectionView.ContentOffset and, only when the old offset was CGPoint.Empty and UIKit changed it, resets scroll tracking and assigns the old offset back. This is a post-layout offset-restoration strategy. Alternative candidates must use a different root-cause mechanism rather than relocating or cosmetically rewriting the same capture/restore check.

The PR also adds the Issue36422 HostApp page, UI test, and platform snapshots. Existing Issue34636.VerticalItemsRemainFullyVisibleAfterChangingSpacing snapshots changed, making that existing test the directly relevant regression check.

Completed Gate

Gate result is FAILED and must not be rerun. Both without-fix and with-fix gate runs stopped at the same compile error:

Issue36422.cs(18,15): error MAUI0003: Test method
'ChangingItemSpacingDoesNotShiftFirstItemOutOfView' uses the sharded category
'CollectionView' directly; use
[ShardedTestCategory(UITestCategories.CollectionView, shard: ...)]

The added UI test uses [Category(UITestCategories.CollectionView)], contrary to the repository rule requiring method-level ShardedTestCategory for CollectionView tests. The try-fix restoration boundary is expected to allow changes only to the reverted production fix file, so candidates must not modify the added test file unless .github/.baseline-state.json explicitly lists it in RevertedFiles. Record the compile failure honestly if this unchanged PR test blocks validation.

Bounded Validation

Use exactly one combined filtered UI-test command per implementation pass; it covers the detected primary test and the mandatory directly related regression test without running a broader suite:

pwsh .github/scripts/BuildAndRunHostApp.ps1 -Platform ios -TestFilter "FullyQualifiedName~ChangingItemSpacingDoesNotShiftFirstItemOutOfView|FullyQualifiedName~VerticalItemsRemainFullyVisibleAfterChangingSpacing"

Do not run gate verification or any unrequested full/category suite. Each candidate gets one implementation/test pass and at most one focused correction/retest.

Applicable Constraints

  • iOS/MacCatalyst uses the active Handlers/Items2/iOS/ implementation.
  • Keep invalidation scoped and keep measure/layout state synchronized.
  • This is a CollectionView layout/scrolling hot path: avoid LINQ, captures, and unnecessary allocation or global invalidation.
  • UIKit mutations must remain on the UI thread.
  • Do not add or alter public API.
  • Follow the try-fix skill's baseline allow-list, artifact, inline expert self-review, and script-only restore requirements.
  • The mechanical regression cross-reference reported CLEAN with no recent labeled fix overlap.

🔬 Code Review — Deep Analysis

Code Review — PR #37032

Independent Assessment

What this changes: On iOS and MacCatalyst, the Items2 CollectionView handler captures the native content offset before replacing its compositional layout. If the collection was at CGPoint.Empty and UIKit shifts it during the replacement, the change resets scroll tracking and restores the origin.

Inferred motivation: Rebuilding a self-sizing compositional layout after an ItemSpacing change can make UIKit reconcile estimated sizes by moving the viewport, hiding the first item even though the collection was at its origin.

Reconciliation with PR Narrative

The submitted implementation matches the stated origin-drift failure mechanism and uses the existing ResetScrollTracking() convention before assigning ContentOffset. The implementation deliberately leaves non-origin positions to UIKit rather than forcing every layout replacement back to zero.

Blast Radius Assessment

  • Runs for all instances: It runs for every Items2 layout replacement, but restores state only when the prior offset is exactly CGPoint.Empty and the replacement shifted it.
  • Startup impact: No direct startup or initialization impact.
  • Static/shared state: None introduced.
  • Adjacent scenarios: Layout replacements for empty, grouped, horizontal, grid, and reconnecting collections traverse the same method. No concrete production-code defect was proven for those cases, but runtime safety remains unverified because the added regression test does not compile.

CI / Gate Status

  • Gate result: Failed before test execution.
  • Classification: PR-caused compile failure.
  • Evidence: Issue36422.ChangingItemSpacingDoesNotShiftFirstItemOutOfView uses the sharded CollectionView category directly, triggering MAUI0003 and preventing Controls.TestCases.iOS.Tests from compiling.
  • Action: Do not rerun the gate. Correct the test attribute in the refinement candidate, then run the single bounded iOS validation command once.

Findings

❌ Error — Added regression test cannot compile

src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue36422.cs:17 uses [Category(UITestCategories.CollectionView)]. CollectionView UI tests require method-level [ShardedTestCategory(UITestCategories.CollectionView, shard: ...)]; MAUI0003 therefore blocks compilation and neither the new regression test nor the directly related spacing test executes.

Failure-Mode Probing

  • Non-origin viewport: The condition does not overwrite a scrolled position; UIKit remains responsible for preserving it.
  • UIKit does not shift the origin: No offset assignment or tracking reset occurs.
  • Empty or initial collections: The code performs no item lookup and only restores the captured native offset if UIKit changes it.
  • Handler reconnect/layout replacement: No shared or retained state is added; the decision uses values local to each replacement.
  • Horizontal and inset origins: The exact CGPoint.Empty predicate is narrower than a semantic content origin such as (-AdjustedContentInset.Left, -AdjustedContentInset.Top). This is a residual coverage question, not a proven defect for the reported scenario.

External Output Contract

Not applicable.

Verdict: NEEDS_CHANGES

Confidence: low

Summary: The production mitigation is localized and coherent for the reported origin-drift scenario, but the PR's new regression test is unbuildable. Fixing the sharding attribute is required before the behavior can be validated, so the submitted PR is not ready as-is.


🛠️ Try-Fix — Analysis & Comparison

Try-Fix Result (Candidate 1)

Approach: First-item semantic re-anchor after layout rebuild: when the view is already at origin and first item is visible pre-swap, call ScrollToItem(0,0, Top/Left, false) immediately after SetCollectionViewLayout.

Prior Approach Avoided: Existing PR captures ContentOffset immediately before SetCollectionViewLayout, then conditionally restores CGPoint.Empty afterward with reset scroll tracking. That snapshot/restore mechanism depends on restoring prior pixel offset state.

Mechanism-Level Difference: This candidate treats runtime spacing change as logical anchor-loss during compositional layout recomputation. Instead of restoring prior pixel offset, it re-establishes semantic anchor identity (item 0,0 at top/leading) after layout swap, so UIKit offset drift does not leave the first item hidden.

Files Changed:

  • src/Controls/src/Core/Handlers/Items2/iOS/ItemsViewController2.cs

Result: ❌ FAIL

Self-Review: 0 findings (0 critical, 0 major, 0 moderate/minor) — see
eviewer-findings.json

Test Command:

pwsh .github/scripts/BuildAndRunHostApp.ps1 -Platform ios -TestFilter "FullyQualifiedName~ChangingItemSpacingDoesNotShiftFirstItemOutOfView|FullyQualifiedName~VerticalItemsRemainFullyVisibleAfterChangingSpacing"

Test Result: Failed at compile step with �rror MAUI0003 in src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue36422.cs (invalid direct CollectionView category).

Failure/Blocker Analysis: .github/.baseline-state.json allow-list exposed exactly one editable file (ItemsViewController2.cs). The failing test file was not in RevertedFiles, so it was not modified.

Artifact Directory: CustomAgentLogsTmp/PRState/37032/PRAgent/try-fix/attempt-1

Captured Diff:
`diff
diff --git a/src/Controls/src/Core/Handlers/Items2/iOS/ItemsViewController2.cs b/src/Controls/src/Core/Handlers/Items2/iOS/ItemsViewController2.cs
index 5de9f0c3e9..b530874720 100644
--- a/src/Controls/src/Core/Handlers/Items2/iOS/ItemsViewController2.cs
+++ b/src/Controls/src/Core/Handlers/Items2/iOS/ItemsViewController2.cs
@@ -303,11 +303,73 @@ namespace Microsoft.Maui.Controls.Handlers.Items2
Delegator = CreateDelegator();
CollectionView.Delegate = Delegator;

  •   	bool shouldAnchorFirstItemAtStart = ShouldAnchorFirstItemAtStart();
      	CollectionView.SetCollectionViewLayout(ItemsViewLayout, false);
    
  •   	AnchorFirstItemAtStartIfNeeded(shouldAnchorFirstItemAtStart);
    
      	UpdateEmptyView();
      }
    
  •   bool ShouldAnchorFirstItemAtStart()
    
  •   {
    
  •   	var collectionView = CollectionView;
    
  •   	var itemsSource = ItemsSource;
    
  •   	if (collectionView is null || itemsSource is null || itemsSource.ItemCount == 0)
    
  •   	{
    
  •   		return false;
    
  •   	}
    
  •   	if (IsHorizontal)
    
  •   	{
    
  •   		if (collectionView.ContentOffset.X > -collectionView.ContentInset.Left)
    
  •   		{
    
  •   			return false;
    
  •   		}
    
  •   	}
    
  •   	else if (collectionView.ContentOffset.Y > -collectionView.ContentInset.Top)
    
  •   	{
    
  •   		return false;
    
  •   	}
    
  •   	var visibleIndexPaths = collectionView.IndexPathsForVisibleItems;
    
  •   	if (visibleIndexPaths is null || visibleIndexPaths.Length == 0)
    
  •   	{
    
  •   		return false;
    
  •   	}
    
  •   	var visibleIndexPathsLength = visibleIndexPaths.Length;
    
  •   	for (int n = 0; n < visibleIndexPathsLength; n++)
    
  •   	{
    
  •   		var indexPath = visibleIndexPaths[n];
    
  •   		if (indexPath.Section == 0 && indexPath.Item == 0)
    
  •   		{
    
  •   			return true;
    
  •   		}
    
  •   	}
    
  •   	return false;
    
  •   }
    
  •   void AnchorFirstItemAtStartIfNeeded(bool shouldAnchorFirstItemAtStart)
    
  •   {
    
  •   	if (!shouldAnchorFirstItemAtStart || CollectionView is null || ItemsSource is null)
    
  •   	{
    
  •   		return;
    
  •   	}
    
  •   	var firstItemIndexPath = NSIndexPath.FromItemSection(0, 0);
    
  •   	if (!Items.IndexPathHelpers.IsIndexPathValid(ItemsSource, firstItemIndexPath))
    
  •   	{
    
  •   		return;
    
  •   	}
    
  •   	(Delegator as IScrollTrackingDelegator)?.ResetScrollTracking();
    
  •   	CollectionView.ScrollToItem(
    
  •   		firstItemIndexPath,
    
  •   		IsHorizontal ? UICollectionViewScrollPosition.Left : UICollectionViewScrollPosition.Top,
    
  •   		false);
    
  •   }
    
  •   protected virtual UICollectionViewDelegateFlowLayout CreateDelegator()
      {
      	return new ItemsViewDelegator2<TItemsView, ItemsViewController2<TItemsView>>(ItemsViewLayout, this);
    

`

Restore Confirmation: pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore executed; Restored True = True.

This Attempt's Status: Done
Reasoning: Approach implemented and validated once; command failed due to existing compile error outside allow-list.

Try-Fix Result (Candidate 2)

Approach: Settle self-sizing before a same-axis linear CollectionView layout swap. For an initialized collection, reload the existing cells and synchronously run LayoutIfNeeded while the old native layout still provides stable geometry, then install the replacement compositional layout without a second post-swap reload. Non-linear, axis-changing, initial, and CarouselView transitions retain the original post-swap reload order.

Prior Approaches Avoided: The PR captures the pixel ContentOffset around SetCollectionViewLayout, then conditionally writes CGPoint.Empty back and resets scroll tracking after UIKit shifts it. Candidate 1 instead records whether the first item is at the start and repairs the post-swap viewport by calling ScrollToItem(0, 0, Top/Left, false). Both earlier mechanisms act after UIKit has chosen a shifted viewport: one restores coordinates and one issues a semantic scroll.

Mechanism-Level Difference: Candidate 2 neither reads nor writes ContentOffset, resets scroll tracking, selects an index path, nor issues a scroll. Its root-cause hypothesis is that the current post-swap ReloadData makes estimated-to-preferred cell-size reconciliation happen after the new layout becomes active, so UIKit preserves provisional geometry by shifting the viewport. Reloading and resolving preferred sizes before the same-axis linear transition removes that post-transition data/measurement phase; the replacement layout starts from settled cells instead of correcting viewport position after drift has occurred.

Files Changed:

  • src/Controls/src/Core/Handlers/Items2/iOS/ItemsViewController2.cs (captured candidate diff only)

Result: ❌ FAIL

Exact Test Command:

pwsh .github/scripts/BuildAndRunHostApp.ps1 -Platform ios -TestFilter "FullyQualifiedName~ChangingItemSpacingDoesNotShiftFirstItemOutOfView|FullyQualifiedName~VerticalItemsRemainFullyVisibleAfterChangingSpacing"

Test Result: The HostApp built and deployed successfully. Compilation of Controls.TestCases.iOS.Tests then failed before either filtered test executed:

src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue36422.cs(18,15): error MAUI0003: Test method 'ChangingItemSpacingDoesNotShiftFirstItemOutOfView' uses the sharded category 'CollectionView' directly; use `[ShardedTestCategory(UITestCategories.CollectionView, shard: ...)]`

Failure/Blocker Analysis: .github/.baseline-state.json contained NewFiles: [] and exactly one RevertedFiles entry: src/Controls/src/Core/Handlers/Items2/iOS/ItemsViewController2.cs. The unchanged Issue36422 UI test is outside that allow-list, so the known analyzer error could not be corrected. The required command was run once; no correction or retest was attempted because the failure was unrelated to the candidate and required an out-of-scope tracked-file edit. Runtime behavior of candidate 2 therefore remains unverified.

Self-Review: Final findings count: 0 (reviewer-findings.json is []). The inline review initially found one major adjacent-scenario defect: moving every reload before the swap could measure axis-changing layouts or Grid Span changes against old geometry and cache an invalid MeasureFirstItem size. A single pre-test correction scoped pre-settling to same-axis linear CollectionView transitions and preserved the original post-swap reload for all other transitions. The corrected final diff was reviewed again and was clean.

Artifact Directory: CustomAgentLogsTmp/PRState/37032/PRAgent/try-fix/attempt-2

Captured Diff:

diff --git a/src/Controls/src/Core/Handlers/Items2/iOS/ItemsViewController2.cs b/src/Controls/src/Core/Handlers/Items2/iOS/ItemsViewController2.cs
index 5de9f0c3e9..d95e00f7de 100644
--- a/src/Controls/src/Core/Handlers/Items2/iOS/ItemsViewController2.cs
+++ b/src/Controls/src/Core/Handlers/Items2/iOS/ItemsViewController2.cs
@@ -61,6 +61,13 @@ namespace Microsoft.Maui.Controls.Handlers.Items2
 			if (CollectionView.CollectionViewLayout == newLayout)
 				return;
 
+			bool settleCellsBeforeLayoutSwap =
+				_initialized &&
+				ItemsView is CollectionView { ItemsLayout: LinearItemsLayout } &&
+				CollectionView.CollectionViewLayout is UICollectionViewCompositionalLayout currentLayout &&
+				newLayout is UICollectionViewCompositionalLayout replacementLayout &&
+				currentLayout.Configuration.ScrollDirection == replacementLayout.Configuration.ScrollDirection;
+
 			if (newLayout is UICollectionViewCompositionalLayout compositionalLayout)
 			{
 				// Note: on carousel layout, the scroll direction is always vertical to achieve horizontal paging with snapping.
@@ -69,12 +76,19 @@ namespace Microsoft.Maui.Controls.Handlers.Items2
 				ScrollDirection = compositionalLayout.Configuration.ScrollDirection;
 			}
 
+			if (settleCellsBeforeLayoutSwap)
+			{
+				// Resolve self-sized cells against stable geometry before replacing the layout.
+				ReloadData();
+				CollectionView.LayoutIfNeeded();
+			}
+
 			ItemsViewLayout = newLayout;
 			_initialized = false;
 
 			EnsureLayoutInitialized();
 
-			if (_initialized)
+			if (_initialized && !settleCellsBeforeLayoutSwap)
 			{
 				// Reload the data so the currently visible cells get laid out according to the new layout
 				ReloadData();

Restore Confirmation: After artifact capture and the artifact gate, the exact command pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore completed with Restored True. The candidate production change is no longer present in the working tree.

This Attempt's Status: Done

Reasoning: Candidate 2 implemented and reviewed one genuinely different prevention mechanism, but the sole bounded validation run was stopped by the pre-existing, non-allow-listed MAUI0003 test compile error.


📝 PR Finalize — Recommended Title & Description

Assessment: ✏️ Recommend updating — the current metadata is detailed but the title has awkward wording and spacing, while the description should state that offset restoration is deliberately limited to the origin.

Recommended title

[iOS/MacCatalyst] CollectionView: Preserve visible position when item spacing changes

Recommended description

### Issue Details

On iOS/MacCatalyst, increasing `CollectionView.ItemSpacing` at runtime can silently shift `ContentOffset`, hiding the first item until the user manually scrolls up.

### Root Cause

- File: `src/Controls/src/Core/Handlers/Items2/iOS/ItemsViewController2.cs`
- Any spacing/span change routes through `CollectionViewHandler2.OnItemsLayoutPropertyChanged` → `UpdateLayout()` → `ItemsViewController2.UpdateLayout(newLayout)` → `EnsureLayoutInitialized()`.
- `EnsureLayoutInitialized()` builds and swaps in a new `UICollectionViewCompositionalLayout` instance through `CollectionView.SetCollectionViewLayout(ItemsViewLayout, false)`.
- Because CollectionView items use self-sizing/estimated dimensions (`NSCollectionLayoutDimension.CreateEstimated(30f)`), UIKit reconciles the new layout without a prior size cache and can synchronously shift `ContentOffset` during that call.
- Logging confirmed that `ContentOffset.Y` moved `0` → `22.5` → `42.5` → `142.5` as spacing increased `20` → `50` → `100` → `150`, with all drift occurring inside `SetCollectionViewLayout` and no further drift afterward.

### Description of Change

- Captures `ContentOffset` before replacing the layout.
- When the captured offset is `CGPoint.Empty` and UIKit shifts it during the replacement, calls `ResetScrollTracking()` and restores the origin.
- Leaves non-origin offsets untouched so UIKit continues preserving positions that are already scrolled away from the top.
- Uses the existing `ResetScrollTracking()` + `ContentOffset` assignment pattern from `UpdateItemsSource()`.
- Adds the `Issue36422` HostApp reproduction, UI test, and platform snapshots.

### Issues Fixed

Fixes #36422

**Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac

| Before | After |
|--------|-------|
| <Video src="https://github.com/user-attachments/assets/3b6117a5-216c-4cb6-bab5-3fa02e00715b" Width="300" Height="600" /> | <Video src="https://github.com/user-attachments/assets/4bb43152-6f8c-492e-b4ab-e2958081c720" Width="300" Height="600" /> |

🏁 Report — Final Recommendation

⚠️ Final Recommendation: REQUEST CHANGES

Winner: pr-plus-reviewer

pr-plus-reviewer preserves the submitted PR's localized production fix and applies the expert reviewer's required one-line test correction. It is the only candidate whose bounded validation completed: the iOS HostApp and test assembly built successfully, and both ChangingItemSpacingDoesNotShiftFirstItemOutOfView and VerticalItemsRemainFullyVisibleAfterChangingSpacing passed.

The submitted pr cannot win because its new regression test uses the sharded CollectionView category directly, causing MAUI0003 before either selected test can execute. Since the winning correction is not present in the submitted PR HEAD, the recommendation is REQUEST CHANGES.

Comparative Ranking

Rank Candidate Validation Assessment
1 pr-plus-reviewer ✅ PASS — 2/2 targeted iOS tests passed Best candidate. It keeps the minimal origin-only offset restoration and fixes the PR-caused test compilation error with the repository-standard method-level shard attribute.
2 pr ❌ FAIL — MAUI0003 before test execution The production change is localized and technically coherent, but the submitted test cannot compile. Its behavior therefore was not validated in the raw candidate.
3 try-fix-1 ❌ FAIL — MAUI0003 before test execution The semantic ScrollToItem re-anchor remained unverified and adds item visibility scans, index-path validation, and a native scroll operation to a hot layout path. It has more adjacent-scenario risk than the submitted coordinate restoration.
4 try-fix-2 ❌ FAIL — MAUI0003 before test execution The pre-settlement strategy remained unverified and changes reload/measurement ordering for same-axis linear transitions. Despite its corrected scope, it is a broader behavioral intervention than the winning patch.

All candidates whose required command failed are ranked below the candidate whose regression tests passed. For pr, try-fix-1, and try-fix-2, the failure occurred at test compilation rather than as an assertion failure; no runtime pass may be inferred.

Expert Review

The expert reviewer found one blocking error on the submitted diff: Issue36422.cs used [Category(UITestCategories.CollectionView)], which violates the CollectionView sharding contract and triggers MAUI0003. No concrete defect was established in the production offset-restoration logic. The fix runs only during Items2 layout replacement, introduces no static state, leaves non-origin offsets untouched, and resets scroll tracking before restoring the origin.

Required Change

Apply pr-plus-reviewer/reviewer.patch to the submitted PR. No production-code change beyond the current PR implementation is recommended by this comparison.


📱 UI Tests — CollectionView

Detected UI test categories: CollectionView

⚠️ Deep UI tests — The deep UI run for 1 category (CollectionView) started (the HostApp built and dotnet test launched) but produced no results — the app failed to launch or the test host crashed before a .trx was written (an app-launch/Appium failure or an emulator flake). These categories exited quickly, well under their time budget, so raising the budget will not help — re-run the review to try again. If it recurs, check the build-output.log + logcat in the drop-deep-uitests artifact for an app-startup crash.


🧭 Next Steps — reviewer changes required

The reviewer-enhanced candidate identified changes that are not yet in the submitted PR.

Why: pr-plus-reviewer preserves the submitted production fix while correcting the PR-caused MAUI0003 test-category error. It is the only candidate whose bounded iOS validation completed, with both the new regression test and the directly related spacing test passing.

Address the actionable findings in this review before merging.

@kubaflo

kubaflo commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Expert Review — 0 findings

Reviewed commit 0b18c80.

@MauiBot

MauiBot commented Oct 18, 2026

Copy link
Copy Markdown
Collaborator

PR Test Gate

@KarthikRajaKalaimani — existing-test verification for commit 0b18c807.

Result FAILED Platform iOS Commit 0b18c807


🧪 Gate analysis — click to expand

❌ Failed. The selected tests did not meet the expected outcomes. Inspect the evidence before changing the test or fix.

🖥 UI tests
Test group Without fix With fix
Issue36422 ⚠ Build blocked ⚠ Build blocked
Issue34636 ⚠ Build blocked ⚠ Build blocked
Execution log excerpts

Without fix Issue36422

/Users/cloudtest/vss/_work/1/s/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue36422.cs(18,15): error MAUI0003: Test method 'ChangingItemSpacingDoesNotShiftFirstItemOutOfView' uses the sharded category 'CollectionView' directly; use `[ShardedTestCategory(UITestCategories.CollectionView, shard: ...)]` so both the umbrella and CI shard categories are registered [/Users/cloudtest/vss/_work/1/s/src/Controls/tests/TestCases.iOS.Tests/Controls.TestCases.iOS.Tests.csproj]

With fix Issue36422

/Users/cloudtest/vss/_work/1/s/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue36422.cs(18,15): error MAUI0003: Test method 'ChangingItemSpacingDoesNotShiftFirstItemOutOfView' uses the sharded category 'CollectionView' directly; use `[ShardedTestCategory(UITestCategories.CollectionView, shard: ...)]` so both the umbrella and CI shard categories are registered [/Users/cloudtest/vss/_work/1/s/src/Controls/tests/TestCases.iOS.Tests/Controls.TestCases.iOS.Tests.csproj]

Without fix Issue34636

/Users/cloudtest/vss/_work/1/s/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue36422.cs(18,15): error MAUI0003: Test method 'ChangingItemSpacingDoesNotShiftFirstItemOutOfView' uses the sharded category 'CollectionView' directly; use `[ShardedTestCategory(UITestCategories.CollectionView, shard: ...)]` so both the umbrella and CI shard categories are registered [/Users/cloudtest/vss/_work/1/s/src/Controls/tests/TestCases.iOS.Tests/Controls.TestCases.iOS.Tests.csproj]

With fix Issue34636

/Users/cloudtest/vss/_work/1/s/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue36422.cs(18,15): error MAUI0003: Test method 'ChangingItemSpacingDoesNotShiftFirstItemOutOfView' uses the sharded category 'CollectionView' directly; use `[ShardedTestCategory(UITestCategories.CollectionView, shard: ...)]` so both the umbrella and CI shard categories are registered [/Users/cloudtest/vss/_work/1/s/src/Controls/tests/TestCases.iOS.Tests/Controls.TestCases.iOS.Tests.csproj]

PR head: 0b18c807.

Without-fix baseline: 3a7d7287.

@kubaflo kubaflo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like there are build failures

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

One or more issues must be addressed before approval.

2 open issues
1 previously missed issue

In code that hasn't changed since last review

Medium severity Exclude screenshot test from unsupported platforms

src/​Controls/​tests/​TestCases.Shared.Tests/​Tests/​Issues/​Issue36422.cs:25

IssueAttribute.PlatformsAffected is only metadata; the shared UI-test assembly compiles and discovers this class on every target. As written, this screenshot test also runs on Android and Windows even though both the HostApp page and the fix are scoped to iOS/MacCatalyst, so it can fail on unrelated rendering and does not exercise the changed handler there. Guard the file with #if TEST_FAILS_ON_WINDOWS && TEST_FAILS_ON_ANDROID (as Issue35859.cs does) or otherwise exclude non-iOS targets.

1 resolved since last review

Review effort: Lite

@vishnumenon2684

This comment has been minimized.

@azure-pipelines

This comment has been minimized.

@kubaflo

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

Tests Failure Analysis

@KarthikRajaKalaimani — test-failure analysis for commit 170aa40.

Scope CI failures Commit 170aa40


🧪 CI Analysis — click to expand
📊 maui-pr

No failures found.


🧪 maui-pr-devicetests

No failures found.


🧪 maui-pr-uitests

🧭 Follow-up — actions and refresh

Next action: Restore complete UI diagnostics and same-runtime comparisons before attributing unresolved failures.

Maintainers: comment /review tests to refresh this report.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-controls-collectionview CollectionView, CarouselView, IndicatorView community ✨ Community Contribution partner/syncfusion Issues / PR's with Syncfusion collaboration platform/android platform/ios platform/macos macOS / Mac Catalyst platform/windows s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-win AI found a better alternative fix than the PR s/agent-gate-failed AI could not verify tests catch the bug s/agent-review-in-progress AI review is currently running for this PR s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants