Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 56 additions & 2 deletions src/Controls/src/Core/Handlers/Items2/ItemsViewHandler2.iOS.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
141 changes: 141 additions & 0 deletions src/Controls/tests/TestCases.HostApp/Issues/Issue32983.cs
Original file line number Diff line number Diff line change
@@ -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<Issue32983Item> ListOfStuff { get; } = new();
}
Original file line number Diff line number Diff line change
@@ -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();
Comment thread
BagavathiPerumal marked this conversation as resolved.
Resolved
}
}
#endif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading