Repository navigation
[iOS] CollectionView2: Fix layout for dynamically rebuilt item content - #37437
Conversation
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>
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 37437Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 37437" |
|
Azure Pipelines: Successfully started running 1 pipeline(s). There may be pipelines that require an authorized user to comment /azp run to run. |
Runtime evidenceI 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: The fix explicitly schedules the arrange pass that Empirical checks:
@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. |
There was a problem hiding this comment.
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.PreferredLayoutAttributesFittingAttributesafter 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
|
Hey @jfversluis, |
kubaflo
left a comment
There was a problem hiding this comment.
THis will probably significantly decrease the performance
This comment has been minimized.
This comment has been minimized.
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
left a comment
There was a problem hiding this comment.
Expert Review — 2 findings
See inline comments for details.
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
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
|
/azp run maui-pr |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
|
/azp run maui-pr-uitests |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
|
/azp run maui-pr |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
|
/azp run maui-pr |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
|
/azp run maui-pr-uitests |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
kubaflo
left a comment
There was a problem hiding this comment.
This one is good, but I'm waiting for @morning4coffe-dev to analyse performance - @jfversluis copilot please stop doing /azp run
|
Exercised this PR with the native device-performance tooling from #38274 ( Compared base Scenario:
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 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. |
#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
#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
#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
<!-- 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>



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
CollectionViewHandler2item lifecycle on iOS and MacCatalyst.Root Cause
The reporter's item template rebuilds nested
Gridchildren 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
BindingContextbeforeToPlatform(), matching CV1 so dynamic children exist when the native tree is created.Size.Zeroas a sentinel, and reset per-binding/reuse state while retaining theMeasureFirstItemconstraint cache.Runtime and Performance Evidence
#FFFFFFFF); with this fix, it passes.837a13601924passesIssue37427,Issue33604(safe-area rotation),Issue35859(MeasureFirstItem),Issue33130(grouped header sizing), andIssue33308(CarouselView vertical snapping).+5.2%median delta and MacCatalyst a neutral+0.6%; base/head ranges overlapped, and all operation-level correctness and target-position checks passed.{X=448,Y=156,Width=789,Height=592}inside a1920x1080desktop 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.LayoutSubviews, safe-area transitions, desktop coordinate mapping, color-profile tolerance, and the hot path.What Not to Do
ScrollToor accessibility geometry for this regression; the extra repair cycle can make the broken implementation pass while pixels remain the discriminating signal.SetNeedsLayout(); UIKit may coalesce or skip the relevant pass when a recycled frame is unchanged.Issues Fixed
Fixes #37427