Skip to content

[iOS] CollectionView2: Fix layout for dynamically rebuilt item content - #37437

Merged
kubaflo merged 17 commits into
inflight/currentfrom
jfversluis-fix-ios-collectionview-zero-width
Sep 8, 2026
Merged

kubaflo merged 17 commits into
inflight/currentfrom
jfversluis-fix-ios-collectionview-zero-width

Conversation

@jfversluis

@jfversluis jfversluis commented Aug 14, 2026 •

Copy link
Copy Markdown
Member

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!

Description of Change

Fixes #37427 by correcting the CollectionViewHandler2 item lifecycle on iOS and MacCatalyst.

Root Cause

The reporter's item template rebuilds nested Grid children from a bindable-property callback. CV2 created the platform tree before applying the item binding context, unlike CV1. On realization or reuse, UIKit can then retain the cell frame while the newly generated MAUI subtree has not received the synchronous arrange needed to paint its content. Accessibility geometry can still report non-zero bounds, so geometry-only assertions do not detect the visual failure.

Fix

  • Apply the item BindingContext before ToPlatform(), matching CV1 so dynamic children exist when the native tree is created.
  • Synchronously arrange the measured subtree during preferred sizing so an unchanged recycled frame cannot leave new content unpainted.
  • Preserve invalidations raised during measure/arrange and distinguish external invalidations from arrange-induced reentry; external same-size changes arrange immediately, while arrange-induced same-size work converges through descendant native layout without a duplicate cell arrange.
  • Track arranged validity explicitly instead of using Size.Zero as a sentinel, and reset per-binding/reuse state while retaining the MeasureFirstItem constraint cache.
  • Reconcile changed final UIKit bounds only when they remain compatible with the measured constraints.
  • Reconcile position-dependent cell safe area only for roots with explicit non-uniform edges (or a stale override that must be cleared), avoiding window-coordinate conversion on ordinary cell layout passes.
  • Run the regression on MacCatalyst as well as iOS because both use this handler.

Runtime and Performance Evidence

  • The rendered-pixel regression performs one non-inertial gesture, selects fully visible realized cards, and samples the expected red/orange/gold/green/blue segment centers. iOS derives and verifies isotropic Retina scaling from its full-screen Appium window. Mac2 uses the repository's established 1:1 absolute desktop coordinate model and verifies that the app window and every sampled preview remain contained, preventing accidental desktop/wallpaper sampling. Channel-order checks tolerate color-profile conversion while still rejecting blank/gray pixels.
  • With the production mechanisms removed, the test fails deterministically on Card 7 with white (#FFFFFFFF); with this fix, it passes.
  • A clean iOS run at head 837a13601924 passes Issue37427, Issue33604 (safe-area rotation), Issue35859 (MeasureFirstItem), Issue33130 (grouped header sizing), and Issue33308 (CarouselView vertical snapping).
  • The trusted 1,000-item device performance scenario completed ABBA runs on both platforms. iOS measured a neutral +5.2% median delta and MacCatalyst a neutral +0.6%; base/head ranges overlapped, and all operation-level correctness and target-position checks passed.
  • A separate 1,000-item, 60-gesture instrumentation run recorded 350 binds, 349 measurements, 349 inline arrangements, and 0 final duplicate arrangements. Normal cells skip safe-area geometry work.
  • UI CI exposed a non-full-screen Mac2 window ({X=448,Y=156,Width=789,Height=592} inside a 1920x1080 desktop screenshot), proving that window-size ratios are not valid desktop scaling. The corrected gate now follows the same coordinate model as the shared Mac screenshot helper. The final Mac test assembly builds locally; local runtime remains blocked before fixture setup because WebDriverAgentMac times out while enabling automation mode, so the corrected Mac assertion is being revalidated by CI.
  • Independent lifecycle, performance, coordinate-model, and final pixel-gate reviewers found no blocking issues after tracing reuse, invalidation merging, pre-measure LayoutSubviews, safe-area transitions, desktop coordinate mapping, color-profile tolerance, and the hot path.

What Not to Do

  • Do not rely on settled ScrollTo or accessibility geometry for this regression; the extra repair cycle can make the broken implementation pass while pixels remain the discriminating signal.
  • Do not rely only on SetNeedsLayout(); UIKit may coalesce or skip the relevant pass when a recycled frame is unchanged.
  • Do not compute position-dependent cell safe area during preferred sizing; the cell origin is not final there.
  • Do not remeasure merely because the effective cell safe-area inset changed; that produced a reproducible layout loop. Reconcile the collection-owned final bounds with one bounded arrange instead.
  • Do not use a shared reference-typed palette in this regression; it suppresses the recycled property-changed callback.

Issues Fixed

Fixes #37427

Ensure cells receive an arrange pass after measurement even when UIKit preserves the existing cell frame. Add a visual regression that dynamically rebuilds item content and verifies recycled cells after scrolling.

Fixes #37427

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI lite review requested due to automatic review settings August 14, 2026 13:56
@github-actions

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 -- 37437

Or

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

@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.

@jfversluis

Copy link
Copy Markdown
Member Author

Runtime evidence

I reproduced the original issue using the reporter's MAUI 10.0.90 sample on an iPhone 16 Pro simulator running iOS 18.4. After scrolling, the recycled cards retained their native frames but their dynamically rebuilt color bars were not painted:

Before: recycled cards render empty color regions

The fix explicitly schedules the arrange pass that TemplatedCell2 had marked as needed. With the final one-line handler change, the same recycled-cell scenario renders every dynamically added bar after scrolling:

After: recycled cards render all color bars

Empirical checks:

  • Local HostApp built against this branch and exercised through Appium on iOS 18.4 and iOS 26.5.
  • The focused visual UI regression passed on both repository baseline environments (iPhone 11 Pro, iOS 18.4 and iOS 26.5).
  • Removing the extra bind-time layout request and retaining only the measurement-boundary SetNeedsLayout() still passed, confirming the minimal fix.
  • Three independent model reviews agreed the handler change is correctly placed and does not create a layout loop; their test-baseline feedback was addressed.

@NightMan665, could you please try the PR artifacts against your original app once the package build finishes? The dogfood command is in the bot comment above. Please let us know whether it fixes the rendering issue in your real scenario.

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.

Pull request overview

This PR addresses a .NET MAUI iOS CollectionView2 (Items2) recycling/layout regression by ensuring a UIKit layout pass occurs after a cell’s content is re-measured and marked for arrange, and adds a UI repro + visual regression coverage for the scenario.

Changes:

  • Trigger a UIKit layout pass from TemplatedCell2.PreferredLayoutAttributesFittingAttributes after measurement invalidation (SetNeedsLayout()).
  • Add a HostApp repro page (Issue37427) that rebuilds dynamic child content during binding updates.
  • Add an iOS visual UI test that scrolls directly to recycled cells and validates via screenshot baselines.
Show a summary per file
File Description
src/Controls/src/Core/Handlers/Items2/iOS/TemplatedCell2.cs Calls SetNeedsLayout() when measurement invalidation occurs so LayoutSubviews runs and the MAUI arrange pass is not skipped for recycled cells.
src/Controls/tests/TestCases.HostApp/Issues/Issue37427.cs Adds a HostApp repro page that dynamically rebuilds item content to reproduce the recycled-cell layout issue.
src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue37427.cs Adds an iOS visual regression test that scrolls to a recycled item and verifies rendering via screenshot.

Review details

  • Files reviewed: 3/5 changed files
  • Comments generated: 1
  • Review effort level: Lite

@NightMan665

Copy link
Copy Markdown

Hey @jfversluis,
It doesn't look to be fixed, unfortunately:
Screenshot 2026-08-14 at 20 55 36
How can I help?

@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.

THis will probably significantly decrease the performance

@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 14, 2026
jfversluis and others added 4 commits August 14, 2026 21:05
Replace the simplified C# test control with the original XAML and source-generated control structure so the regression test exercises the actual failing path.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: d54bb233-b2d7-4d72-99f8-e97a19163011
Capture the reporter's exact XAML scenario with the legacy handler as the known-good rendering oracle.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: d54bb233-b2d7-4d72-99f8-e97a19163011
Two-part fix for #37427:

1. Set BindingContext BEFORE ToPlatform in BindVirtualView (matching CV1's
   order), so property-changed callbacks fire before the handler tree exists
   and children are included in the initial layout pass.

2. Arrange inline in PreferredLayoutAttributesFittingAttributes instead of
   deferring to LayoutSubviews via SetNeedsLayout. UIKit may skip
   LayoutSubviews when the cell frame doesn't change, leaving dynamic
   children unarranged. The inline arrange is zero-cost on the steady-state
   scrolling path (gated by _needsArrange which is only set on content change).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

@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 — 2 findings

See inline comments for details.

MauiBot

This comment was marked as outdated.

@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-win AI found a better alternative fix than the PR s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) and removed s/agent-review-in-progress AI review is currently running for this PR labels Aug 14, 2026
Bind item content before creating its platform tree and arrange measured cells synchronously when UIKit may retain an unchanged recycled-cell frame. Preserve re-entrant measure invalidations raised during arrange.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: d54bb233-b2d7-4d72-99f8-e97a19163011
Copilot AI review requested due to automatic review settings August 14, 2026 22:20
@azure-pipelines

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

@jfversluis

Copy link
Copy Markdown
Member Author

/azp run maui-pr

@azure-pipelines

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

@jfversluis

Copy link
Copy Markdown
Member Author

/azp run maui-pr-uitests

@azure-pipelines

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

@jfversluis

Copy link
Copy Markdown
Member Author

/azp run maui-pr

@azure-pipelines

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

@jfversluis

Copy link
Copy Markdown
Member Author

/azp run maui-pr

@azure-pipelines

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

@jfversluis

Copy link
Copy Markdown
Member Author

/azp run maui-pr-uitests

@azure-pipelines

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

@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.

This one is good, but I'm waiting for @morning4coffe-dev to analyse performance - @jfversluis copilot please stop doing /azp run

@kubaflo

kubaflo commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Exercised this PR with the native device-performance tooling from #38274 (b58ff3b3c5fdcfa6c35fdedad1743020b0d4c973). The selected CollectionView2 scrolling scenario passed on both base and head; these runs did not establish a stable timing improvement or regression.

Compared base 7a2ed62f6de5b9556778c40beda39a7e11d1403f with head 837a136019247c04bf8122b0a543f53917868bff, with identical trusted harness overlays. Environment: Apple M4 Max, iPhone 11 Pro simulator / iOS 26.5, Release net10.0-ios / iossimulator-arm64. Both builds used the documented ValidateXcodeVersion=false override for the installed Xcode 26.6.

Scenario: collectionview-grouped-scrollto-makevisible, explicitly registering CollectionViewHandler2, with 100 items in 5 groups, MeasureAllItems, and animated ScrollTo(MakeVisible) to section 1/item 2. It waits for native position stability and target visibility.

Independent ABBA comparison Base median Head median Delta Tool classification
Unmodified local driver using built apps 684.24 ms 686.45 ms +0.32% neutral
Extracted payload, packaging-only workaround 747.84 ms 688.05 ms -7.99% neutral

Each comparison ran base/head/head/base, with 2 warmups and 10 measured operations per invocation. All 8 native test invocations passed (80 measured operations total), including correctness/provenance checks. Final target position was consistently 620 logical points with zero spread. Both comparisons had overlapping ranges; the opposite delta signs are another reason not to interpret the second result as a demonstrated speedup. Latency includes animation, settling, and polling, rather than isolated layout cost.

The payload-based run required a packaging-script-only workaround for a PowerShell -and continuation defect in #38274, reported there. The first comparison used the unchanged local driver and built apps directly. No product-code changes were made to either target revision.

Important limit: This exercises the handler changed here, but does not validate the dynamically rebuilt item-content pixel fix. The Issue37427 pixel regression was not run. This is scoped local simulator evidence, not whole-PR correctness validation, physical-device benchmarking, other-platform coverage, or AzDO/Helix execution.

@kubaflo
kubaflo changed the base branch from main to inflight/current September 8, 2026 17:28
@kubaflo
kubaflo merged commit a2b5c7c into inflight/current Sep 8, 2026
155 of 163 checks passed
@kubaflo
kubaflo deleted the jfversluis-fix-ios-collectionview-zero-width branch September 8, 2026 17:28
@github-actions github-actions Bot added this to the .NET 10 SR11 milestone Sep 8, 2026
kubaflo pushed a commit that referenced this pull request Sep 9, 2026
#37437)

<!-- Please let the below note in for people that find this PR -->
> [!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

### Description of Change

Fixes #37427 by correcting the `CollectionViewHandler2` item lifecycle
on iOS and MacCatalyst.

### Root Cause

The reporter's item template rebuilds nested `Grid` children from a
bindable-property callback. CV2 created the platform tree before
applying the item binding context, unlike CV1. On realization or reuse,
UIKit can then retain the cell frame while the newly generated MAUI
subtree has not received the synchronous arrange needed to paint its
content. Accessibility geometry can still report non-zero bounds, so
geometry-only assertions do not detect the visual failure.

### Fix

- Apply the item `BindingContext` before `ToPlatform()`, matching CV1 so
dynamic children exist when the native tree is created.
- Synchronously arrange the measured subtree during preferred sizing so
an unchanged recycled frame cannot leave new content unpainted.
- Preserve invalidations raised during measure/arrange and distinguish
external invalidations from arrange-induced reentry; external same-size
changes arrange immediately, while arrange-induced same-size work
converges through descendant native layout without a duplicate cell
arrange.
- Track arranged validity explicitly instead of using `Size.Zero` as a
sentinel, and reset per-binding/reuse state while retaining the
`MeasureFirstItem` constraint cache.
- Reconcile changed final UIKit bounds only when they remain compatible
with the measured constraints.
- Reconcile position-dependent cell safe area only for roots with
explicit non-uniform edges (or a stale override that must be cleared),
avoiding window-coordinate conversion on ordinary cell layout passes.
- Run the regression on MacCatalyst as well as iOS because both use this
handler.

### Runtime and Performance Evidence

- The rendered-pixel regression performs one non-inertial gesture,
selects fully visible realized cards, and samples the expected
red/orange/gold/green/blue segment centers. iOS derives and verifies
isotropic Retina scaling from its full-screen Appium window. Mac2 uses
the repository's established 1:1 absolute desktop coordinate model and
verifies that the app window and every sampled preview remain contained,
preventing accidental desktop/wallpaper sampling. Channel-order checks
tolerate color-profile conversion while still rejecting blank/gray
pixels.
- With the production mechanisms removed, the test fails
deterministically on Card 7 with white (`#FFFFFFFF`); with this fix, it
passes.
- A clean iOS run at head `837a13601924` passes `Issue37427`,
`Issue33604` (safe-area rotation), `Issue35859` (`MeasureFirstItem`),
`Issue33130` (grouped header sizing), and `Issue33308` (CarouselView
vertical snapping).
- The trusted 1,000-item device performance scenario completed ABBA runs
on both platforms. iOS measured a neutral `+5.2%` median delta and
MacCatalyst a neutral `+0.6%`; base/head ranges overlapped, and all
operation-level correctness and target-position checks passed.
- A separate 1,000-item, 60-gesture instrumentation run recorded 350
binds, 349 measurements, 349 inline arrangements, and **0 final
duplicate arrangements**. Normal cells skip safe-area geometry work.
- UI CI exposed a non-full-screen Mac2 window
(`{X=448,Y=156,Width=789,Height=592}` inside a `1920x1080` desktop
screenshot), proving that window-size ratios are not valid desktop
scaling. The corrected gate now follows the same coordinate model as the
shared Mac screenshot helper. The final Mac test assembly builds
locally; local runtime remains blocked before fixture setup because
WebDriverAgentMac times out while enabling automation mode, so the
corrected Mac assertion is being revalidated by CI.
- Independent lifecycle, performance, coordinate-model, and final
pixel-gate reviewers found no blocking issues after tracing reuse,
invalidation merging, pre-measure `LayoutSubviews`, safe-area
transitions, desktop coordinate mapping, color-profile tolerance, and
the hot path.

### What Not to Do

- Do not rely on settled `ScrollTo` or accessibility geometry for this
regression; the extra repair cycle can make the broken implementation
pass while pixels remain the discriminating signal.
- Do not rely only on `SetNeedsLayout()`; UIKit may coalesce or skip the
relevant pass when a recycled frame is unchanged.
- Do not compute position-dependent cell safe area during preferred
sizing; the cell origin is not final there.
- Do not remeasure merely because the effective cell safe-area inset
changed; that produced a reproducible layout loop. Reconcile the
collection-owned final bounds with one bounded arrange instead.
- Do not use a shared reference-typed palette in this regression; it
suppresses the recycled property-changed callback.

### Issues Fixed

Fixes #37427
kubaflo pushed a commit that referenced this pull request Sep 11, 2026
#37437)

<!-- Please let the below note in for people that find this PR -->
> [!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

### Description of Change

Fixes #37427 by correcting the `CollectionViewHandler2` item lifecycle
on iOS and MacCatalyst.

### Root Cause

The reporter's item template rebuilds nested `Grid` children from a
bindable-property callback. CV2 created the platform tree before
applying the item binding context, unlike CV1. On realization or reuse,
UIKit can then retain the cell frame while the newly generated MAUI
subtree has not received the synchronous arrange needed to paint its
content. Accessibility geometry can still report non-zero bounds, so
geometry-only assertions do not detect the visual failure.

### Fix

- Apply the item `BindingContext` before `ToPlatform()`, matching CV1 so
dynamic children exist when the native tree is created.
- Synchronously arrange the measured subtree during preferred sizing so
an unchanged recycled frame cannot leave new content unpainted.
- Preserve invalidations raised during measure/arrange and distinguish
external invalidations from arrange-induced reentry; external same-size
changes arrange immediately, while arrange-induced same-size work
converges through descendant native layout without a duplicate cell
arrange.
- Track arranged validity explicitly instead of using `Size.Zero` as a
sentinel, and reset per-binding/reuse state while retaining the
`MeasureFirstItem` constraint cache.
- Reconcile changed final UIKit bounds only when they remain compatible
with the measured constraints.
- Reconcile position-dependent cell safe area only for roots with
explicit non-uniform edges (or a stale override that must be cleared),
avoiding window-coordinate conversion on ordinary cell layout passes.
- Run the regression on MacCatalyst as well as iOS because both use this
handler.

### Runtime and Performance Evidence

- The rendered-pixel regression performs one non-inertial gesture,
selects fully visible realized cards, and samples the expected
red/orange/gold/green/blue segment centers. iOS derives and verifies
isotropic Retina scaling from its full-screen Appium window. Mac2 uses
the repository's established 1:1 absolute desktop coordinate model and
verifies that the app window and every sampled preview remain contained,
preventing accidental desktop/wallpaper sampling. Channel-order checks
tolerate color-profile conversion while still rejecting blank/gray
pixels.
- With the production mechanisms removed, the test fails
deterministically on Card 7 with white (`#FFFFFFFF`); with this fix, it
passes.
- A clean iOS run at head `837a13601924` passes `Issue37427`,
`Issue33604` (safe-area rotation), `Issue35859` (`MeasureFirstItem`),
`Issue33130` (grouped header sizing), and `Issue33308` (CarouselView
vertical snapping).
- The trusted 1,000-item device performance scenario completed ABBA runs
on both platforms. iOS measured a neutral `+5.2%` median delta and
MacCatalyst a neutral `+0.6%`; base/head ranges overlapped, and all
operation-level correctness and target-position checks passed.
- A separate 1,000-item, 60-gesture instrumentation run recorded 350
binds, 349 measurements, 349 inline arrangements, and **0 final
duplicate arrangements**. Normal cells skip safe-area geometry work.
- UI CI exposed a non-full-screen Mac2 window
(`{X=448,Y=156,Width=789,Height=592}` inside a `1920x1080` desktop
screenshot), proving that window-size ratios are not valid desktop
scaling. The corrected gate now follows the same coordinate model as the
shared Mac screenshot helper. The final Mac test assembly builds
locally; local runtime remains blocked before fixture setup because
WebDriverAgentMac times out while enabling automation mode, so the
corrected Mac assertion is being revalidated by CI.
- Independent lifecycle, performance, coordinate-model, and final
pixel-gate reviewers found no blocking issues after tracing reuse,
invalidation merging, pre-measure `LayoutSubviews`, safe-area
transitions, desktop coordinate mapping, color-profile tolerance, and
the hot path.

### What Not to Do

- Do not rely on settled `ScrollTo` or accessibility geometry for this
regression; the extra repair cycle can make the broken implementation
pass while pixels remain the discriminating signal.
- Do not rely only on `SetNeedsLayout()`; UIKit may coalesce or skip the
relevant pass when a recycled frame is unchanged.
- Do not compute position-dependent cell safe area during preferred
sizing; the cell origin is not final there.
- Do not remeasure merely because the effective cell safe-area inset
changed; that produced a reproducible layout loop. Reconcile the
collection-owned final bounds with one bounded arrange instead.
- Do not use a shared reference-typed palette in this regression; it
suppresses the recycled property-changed callback.

### Issues Fixed

Fixes #37427
kubaflo pushed a commit that referenced this pull request Sep 15, 2026
#37437)

<!-- Please let the below note in for people that find this PR -->
> [!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

### Description of Change

Fixes #37427 by correcting the `CollectionViewHandler2` item lifecycle
on iOS and MacCatalyst.

### Root Cause

The reporter's item template rebuilds nested `Grid` children from a
bindable-property callback. CV2 created the platform tree before
applying the item binding context, unlike CV1. On realization or reuse,
UIKit can then retain the cell frame while the newly generated MAUI
subtree has not received the synchronous arrange needed to paint its
content. Accessibility geometry can still report non-zero bounds, so
geometry-only assertions do not detect the visual failure.

### Fix

- Apply the item `BindingContext` before `ToPlatform()`, matching CV1 so
dynamic children exist when the native tree is created.
- Synchronously arrange the measured subtree during preferred sizing so
an unchanged recycled frame cannot leave new content unpainted.
- Preserve invalidations raised during measure/arrange and distinguish
external invalidations from arrange-induced reentry; external same-size
changes arrange immediately, while arrange-induced same-size work
converges through descendant native layout without a duplicate cell
arrange.
- Track arranged validity explicitly instead of using `Size.Zero` as a
sentinel, and reset per-binding/reuse state while retaining the
`MeasureFirstItem` constraint cache.
- Reconcile changed final UIKit bounds only when they remain compatible
with the measured constraints.
- Reconcile position-dependent cell safe area only for roots with
explicit non-uniform edges (or a stale override that must be cleared),
avoiding window-coordinate conversion on ordinary cell layout passes.
- Run the regression on MacCatalyst as well as iOS because both use this
handler.

### Runtime and Performance Evidence

- The rendered-pixel regression performs one non-inertial gesture,
selects fully visible realized cards, and samples the expected
red/orange/gold/green/blue segment centers. iOS derives and verifies
isotropic Retina scaling from its full-screen Appium window. Mac2 uses
the repository's established 1:1 absolute desktop coordinate model and
verifies that the app window and every sampled preview remain contained,
preventing accidental desktop/wallpaper sampling. Channel-order checks
tolerate color-profile conversion while still rejecting blank/gray
pixels.
- With the production mechanisms removed, the test fails
deterministically on Card 7 with white (`#FFFFFFFF`); with this fix, it
passes.
- A clean iOS run at head `837a13601924` passes `Issue37427`,
`Issue33604` (safe-area rotation), `Issue35859` (`MeasureFirstItem`),
`Issue33130` (grouped header sizing), and `Issue33308` (CarouselView
vertical snapping).
- The trusted 1,000-item device performance scenario completed ABBA runs
on both platforms. iOS measured a neutral `+5.2%` median delta and
MacCatalyst a neutral `+0.6%`; base/head ranges overlapped, and all
operation-level correctness and target-position checks passed.
- A separate 1,000-item, 60-gesture instrumentation run recorded 350
binds, 349 measurements, 349 inline arrangements, and **0 final
duplicate arrangements**. Normal cells skip safe-area geometry work.
- UI CI exposed a non-full-screen Mac2 window
(`{X=448,Y=156,Width=789,Height=592}` inside a `1920x1080` desktop
screenshot), proving that window-size ratios are not valid desktop
scaling. The corrected gate now follows the same coordinate model as the
shared Mac screenshot helper. The final Mac test assembly builds
locally; local runtime remains blocked before fixture setup because
WebDriverAgentMac times out while enabling automation mode, so the
corrected Mac assertion is being revalidated by CI.
- Independent lifecycle, performance, coordinate-model, and final
pixel-gate reviewers found no blocking issues after tracing reuse,
invalidation merging, pre-measure `LayoutSubviews`, safe-area
transitions, desktop coordinate mapping, color-profile tolerance, and
the hot path.

### What Not to Do

- Do not rely on settled `ScrollTo` or accessibility geometry for this
regression; the extra repair cycle can make the broken implementation
pass while pixels remain the discriminating signal.
- Do not rely only on `SetNeedsLayout()`; UIKit may coalesce or skip the
relevant pass when a recycled frame is unchanged.
- Do not compute position-dependent cell safe area during preferred
sizing; the cell origin is not final there.
- Do not remeasure merely because the effective cell safe-area inset
changed; that produced a reproducible layout loop. Reconcile the
collection-owned final bounds with one bounded arrange instead.
- Do not use a shared reference-typed palette in this regression; it
suppresses the recycled property-changed callback.

### Issues Fixed

Fixes #37427
kubaflo added a commit that referenced this pull request Sep 15, 2026
<!-- Please let the below note in for people that find this PR -->
> [!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

### Description of Change

Targets **`inflight/current`** to repair the two compiler/analyzer
failures in `maui-pr` [build
1597590](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1597590).

- Fix **CS1061** in the iOS/Mac Catalyst BlazorWebView scheme handler
introduced by #38141: `BlazorWebViewHandler` has no `Handler` property.
Read the nullable `IViewHandler.VirtualView` property instead,
preserving the disconnected-handler guard and existing empty 404
response. The strongly typed `VirtualView` getter cannot be used for
this check because it throws when disconnected.
- Fix **MAUI0003** in the regression test added by #37437: use
method-level `ShardedTestCategory` with shard 1, registering both the
`CollectionView` umbrella and the `CollectionView1` CI category without
changing the test assertions or platform coverage.

The missing Mac native-artifact publishing error is downstream of the
failed Pack step, so no pipeline workaround is needed. No competing open
repair targeting `inflight/current` was found.

### Issues Fixed

Repairs the `maui-pr` build failures on `inflight/current`; retains the
regression protection for #38131 and the test coverage for #37427.

### Validation

- BlazorWebView project builds for `net10.0-ios26.0` and
`net10.0-maccatalyst26.0`: zero warnings/errors.
- Existing UI-test category analyzer suite: 46 passed.
- Changed files formatted and `git diff --check` clean.

Local validation used the installed .NET 11 preview SDK targeting .NET
10. Full CI has not yet been rerun with the repository-pinned SDK.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) 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.

CollectionView item content renders with zero width on iOS (CollectionViewHandler2)

6 participants