diff --git a/src/Controls/src/Core/Handlers/Items2/ItemsViewHandler2.iOS.cs b/src/Controls/src/Core/Handlers/Items2/ItemsViewHandler2.iOS.cs index c8e8ed19df3d..51f99508f42c 100644 --- a/src/Controls/src/Core/Handlers/Items2/ItemsViewHandler2.iOS.cs +++ b/src/Controls/src/Core/Handlers/Items2/ItemsViewHandler2.iOS.cs @@ -196,11 +196,65 @@ Size EnsureContentSizeForScrollDirection(double widthConstraint, double heightCo var scrollDirection = Controller.GetScrollDirection(); // If contentSize is zero in the relevant dimension (height for vertical, width for horizontal), - // it means none of the content has been realized yet; we need to return the expansive size - // the collection view wants by default to get it to start measuring its content + // it means none of the content has been realized yet. if ((scrollDirection == UICollectionViewScrollDirection.Vertical && contentSize.Height == 0) || (scrollDirection == UICollectionViewScrollDirection.Horizontal && contentSize.Width == 0)) { + var collectionView = Controller.CollectionView; + + // When the CollectionView has not yet been added to a window (pre-mount measurement), + // UICollectionViewCompositionalLayout hasn't run a layout pass and therefore + // CollectionViewContentSize is still zero. Force a layout pass with the given constraints + // so the layout can compute actual content size from its items. + if (collectionView.Window == null) + { + // Local helper to clamp layout constraints to finite, non-negative nfloat values. + nfloat ClampConstraint(double constraint, nfloat fallback) + { + // Treat NaN, infinity, and negative values as invalid and fall back. + if (double.IsNaN(constraint) || double.IsInfinity(constraint) || constraint < 0) + return fallback; + + var value = (nfloat)constraint; + + // Guard against overflow to infinity/NaN or negative after casting. + var valueAsDouble = (double)value; + if (double.IsNaN(valueAsDouble) || double.IsInfinity(valueAsDouble) || value < 0) + return fallback; + + return value; + } + + var previousFrame = collectionView.Frame; + try + { + // Give the CollectionView a finite available size so the layout calculates correctly + var frameWidth = ClampConstraint(widthConstraint, UIView.UILayoutFittingExpandedSize.Width); + var frameHeight = ClampConstraint(heightConstraint, UIView.UILayoutFittingExpandedSize.Height); + + collectionView.Frame = new CoreGraphics.CGRect(0, 0, frameWidth, frameHeight); + collectionView.SetNeedsLayout(); + collectionView.LayoutIfNeeded(); + + // Re-read the content size now that the layout has run + contentSize = Controller.GetSize(); + } + finally + { + // Always restore the original frame + collectionView.Frame = previousFrame; + } + + // If the forced layout produced a valid size, return it directly + if ((scrollDirection == UICollectionViewScrollDirection.Vertical && contentSize.Height > 0) || + (scrollDirection == UICollectionViewScrollDirection.Horizontal && contentSize.Width > 0)) + { + return contentSize; + } + } + + // Fallback: return the expansive size the collection view wants by default + // to get it to start measuring its content var desiredSize = base.GetDesiredSize(widthConstraint, heightConstraint); if (scrollDirection == UICollectionViewScrollDirection.Vertical) { diff --git a/src/Controls/tests/TestCases.HostApp/Issues/Issue32983.cs b/src/Controls/tests/TestCases.HostApp/Issues/Issue32983.cs new file mode 100644 index 000000000000..852684bd116d --- /dev/null +++ b/src/Controls/tests/TestCases.HostApp/Issues/Issue32983.cs @@ -0,0 +1,141 @@ +using System.Collections.ObjectModel; +#if IOS || MACCATALYST +using Microsoft.Maui.Platform; +using UIKit; +#endif + +namespace Maui.Controls.Sample.Issues; + +[Issue(IssueTracker.Github, 32983, "CollectionView messes up Measure operation on Views", PlatformAffected.iOS)] +public class Issue32983 : ContentPage +{ + readonly Label _measuredHeightLabel; + readonly Label _statusLabel; + readonly VerticalStackLayout _rootLayout; + + public Issue32983() + { + _measuredHeightLabel = new Label + { + AutomationId = "MeasuredHeight", + Text = "Pending" + }; + + _statusLabel = new Label + { + AutomationId = "StatusLabel", + Text = "Tap the button to reproduce the issue" + }; + + var showButton = new Button + { + Text = "ShowBottomSheet", + AutomationId = "ShowBottomSheetButton", + HorizontalOptions = LayoutOptions.Fill + }; + showButton.Clicked += OnShowBottomSheetClicked; + + _rootLayout = new VerticalStackLayout + { + Padding = 10, + Spacing = 8, + Children = + { + showButton, + _statusLabel, + new Label { Text = "Measured height (ContentView unmounted):" }, + _measuredHeightLabel + } + }; + + Content = _rootLayout; + } + + void OnShowBottomSheetClicked(object sender, EventArgs e) + { +#if IOS || MACCATALYST + var bottomSheetContent = new Issue32983BottomSheetContentView(); + var vm = new Issue32983ViewModel(); + for (int i = 0; i < 10; i++) + { + vm.ListOfStuff.Add(new Issue32983Item("Item #" + (i + 1))); + } + bottomSheetContent.BindingContext = vm; + + var mauiContext = this.Handler?.MauiContext ?? throw new Exception("MauiContext is null"); + var parent = this.ToUIViewController(mauiContext); + var viewControllerToPresent = bottomSheetContent.ToUIViewController(mauiContext); + + var display = DeviceDisplay.MainDisplayInfo; + double widthDip = display.Width / display.Density; + double heightDip = display.Height / display.Density; + + var minimumSize = bottomSheetContent.Measure(widthDip, heightDip); + var detentSize = minimumSize.ToCGSize(); + + if (OperatingSystem.IsIOSVersionAtLeast(16) || OperatingSystem.IsMacCatalystVersionAtLeast(16)) + { + var detent = UISheetPresentationControllerDetent.Create( + "ContentHeight", + (ctx) => (nfloat)detentSize.Height); + + var sheet = viewControllerToPresent.SheetPresentationController; + if (sheet is not null) + { + sheet.Detents = new[] { detent }; + sheet.LargestUndimmedDetentIdentifier = UISheetPresentationControllerDetentIdentifier.Unknown; + sheet.PrefersScrollingExpandsWhenScrolledToEdge = false; + sheet.PrefersEdgeAttachedInCompactHeight = true; + sheet.WidthFollowsPreferredContentSizeWhenEdgeAttached = true; + } + } + parent.PresentViewController(viewControllerToPresent, animated: true, completionHandler: null); +#endif + } +} + +public class Issue32983BottomSheetContentView : Microsoft.Maui.Controls.ContentView +{ + public Issue32983BottomSheetContentView() + { + BackgroundColor = Colors.AliceBlue; + + var collectionView = new CollectionView + { + SelectionMode = SelectionMode.Single, + VerticalOptions = LayoutOptions.Start, + Margin = new Thickness(10), + AutomationId = "BottomSheetCollectionView", + + ItemsLayout = new LinearItemsLayout(ItemsLayoutOrientation.Vertical), + + ItemTemplate = new DataTemplate(() => + { + var label = new Label + { + FontSize = 20, + FontAttributes = FontAttributes.Bold + }; + + label.SetBinding(Label.TextProperty, nameof(Issue32983Item.Name)); + label.SetBinding(Label.AutomationIdProperty, nameof(Issue32983Item.Name)); + + return label; + }) + }; + + collectionView.SetBinding(ItemsView.ItemsSourceProperty, nameof(Issue32983ViewModel.ListOfStuff)); + + Content = collectionView; + } +} + +public class Issue32983Item(string name) +{ + public string Name => name; +} + +public class Issue32983ViewModel +{ + public ObservableCollection ListOfStuff { get; } = new(); +} diff --git a/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue32983.cs b/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue32983.cs new file mode 100644 index 000000000000..bb2c9168b8c2 --- /dev/null +++ b/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue32983.cs @@ -0,0 +1,26 @@ +// This test is iOS-only: The test sample uses UISheetPresentationController with a custom detent to present a bottom sheet sized to the measured content height. This API is not available on Android or Windows, and on MacCatalyst it ignores custom detents and always presents as a full-height modal. +#if IOS +using NUnit.Framework; +using UITest.Appium; +using UITest.Core; + +namespace Microsoft.Maui.TestCases.Tests.Issues; + +public class Issue32983 : _IssuesUITest +{ + public override string Issue => "CollectionView messes up Measure operation on Views"; + + public Issue32983(TestDevice device) : base(device) { } + + [Test] + [Category(UITestCategories.CollectionView)] + public void BottomSheetDetentHeightIsCorrectWhenCollectionViewIsMeasuredBeforeMount() + { + App.WaitForElement("ShowBottomSheetButton"); + App.Tap("ShowBottomSheetButton"); + + App.WaitForElement("BottomSheetCollectionView"); + VerifyScreenshot(); + } +} +#endif diff --git a/src/Controls/tests/TestCases.iOS.Tests/snapshots/ios-26/BottomSheetDetentHeightIsCorrectWhenCollectionViewIsMeasuredBeforeMount.png b/src/Controls/tests/TestCases.iOS.Tests/snapshots/ios-26/BottomSheetDetentHeightIsCorrectWhenCollectionViewIsMeasuredBeforeMount.png new file mode 100644 index 000000000000..6e8a9ef37955 Binary files /dev/null and b/src/Controls/tests/TestCases.iOS.Tests/snapshots/ios-26/BottomSheetDetentHeightIsCorrectWhenCollectionViewIsMeasuredBeforeMount.png differ diff --git a/src/Controls/tests/TestCases.iOS.Tests/snapshots/ios/BottomSheetDetentHeightIsCorrectWhenCollectionViewIsMeasuredBeforeMount.png b/src/Controls/tests/TestCases.iOS.Tests/snapshots/ios/BottomSheetDetentHeightIsCorrectWhenCollectionViewIsMeasuredBeforeMount.png new file mode 100644 index 000000000000..320359c1c88f Binary files /dev/null and b/src/Controls/tests/TestCases.iOS.Tests/snapshots/ios/BottomSheetDetentHeightIsCorrectWhenCollectionViewIsMeasuredBeforeMount.png differ