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
113 changes: 113 additions & 0 deletions src/Controls/tests/TestCases.HostApp/Issues/Issue34563.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
namespace Maui.Controls.Sample.Issues;

[Issue(IssueTracker.Github, 34563, "[iOS] Vertical SafeAreaEdge isn't respected when Top and Bottom constraints mismatch", PlatformAffected.iOS | PlatformAffected.macOS)]
public class Issue34563 : ContentPage
{
readonly ContentView _parentSafeAreaContainer;
readonly Grid _childSafeAreaContainer;
readonly Label _statusLabel;
bool _parentHandlesTop;

public Issue34563()
{
SafeAreaEdges = new SafeAreaEdges(SafeAreaRegions.None);
BackgroundColor = Colors.Red;

var topMarker = new Label
{
AutomationId = "TopMarker",
BackgroundColor = Colors.LimeGreen,
HeightRequest = 30,
HorizontalOptions = LayoutOptions.Fill,
HorizontalTextAlignment = TextAlignment.Center,
Text = "Top safe-area marker",
VerticalOptions = LayoutOptions.Start,
};

var bottomMarker = new Label
{
AutomationId = "BottomMarker",
BackgroundColor = Colors.Blue,
HeightRequest = 30,
HorizontalOptions = LayoutOptions.Fill,
HorizontalTextAlignment = TextAlignment.Center,
Text = "Bottom safe-area marker",
TextColor = Colors.White,
VerticalOptions = LayoutOptions.End,
};

_statusLabel = new Label
{
AutomationId = "SafeAreaStatusLabel",
HorizontalTextAlignment = TextAlignment.Center,
};

var toggleParentEdgeButton = new Button
{
AutomationId = "ToggleParentEdgeButton",
Text = "Swap parent safe-area edge",
};
toggleParentEdgeButton.Clicked += (_, _) =>
{
_parentHandlesTop = !_parentHandlesTop;
UpdateSafeAreaEdges();
};

var controls = new VerticalStackLayout
{
Spacing = 12,
Margin = 20,
VerticalOptions = LayoutOptions.Center,
Children =
{
new Label
{
Text = "The child handles Top and Bottom while its parent swaps between handling exactly one of those edges.",
HorizontalTextAlignment = TextAlignment.Center,
},
toggleParentEdgeButton,
_statusLabel,
}
};

_childSafeAreaContainer = new Grid
{
AutomationId = "ChildSafeAreaContainer",
};
_childSafeAreaContainer.Add(topMarker);
_childSafeAreaContainer.Add(bottomMarker);
_childSafeAreaContainer.Add(controls);

_parentSafeAreaContainer = new ContentView
{
AutomationId = "ParentSafeAreaContainer",
Content = _childSafeAreaContainer,
};

var rootGrid = new Grid { AutomationId = "RootGrid" };
rootGrid.Add(_parentSafeAreaContainer);

UpdateSafeAreaEdges();
Content = rootGrid;
}

void UpdateSafeAreaEdges()
{
_parentSafeAreaContainer.SafeAreaEdges = new SafeAreaEdges(
SafeAreaRegions.None,
_parentHandlesTop ? SafeAreaRegions.Container : SafeAreaRegions.None,
SafeAreaRegions.None,
_parentHandlesTop ? SafeAreaRegions.None : SafeAreaRegions.Container);

_childSafeAreaContainer.SafeAreaEdges = new SafeAreaEdges(
SafeAreaRegions.None,
SafeAreaRegions.Container,
SafeAreaRegions.None,
SafeAreaRegions.Container);

_statusLabel.Text =
$"Parent: Top={(_parentHandlesTop ? "Container" : "None")}, " +
$"Bottom={(_parentHandlesTop ? "None" : "Container")} | " +
"Child: Top=Container, Bottom=Container";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
#if IOS || MACCATALYST
using NUnit.Framework;
using UITest.Appium;
using UITest.Core;

namespace Microsoft.Maui.TestCases.Tests.Issues
{
public class Issue34563 : _IssuesUITest
{
public override string Issue => "[iOS] Vertical SafeAreaEdge isn't respected when Top and Bottom constraints mismatch";

public Issue34563(TestDevice device) : base(device) { }

[Test]
[Category(UITestCategories.SafeAreaEdges)]
public void SafeAreaEdgesRespectedWhenTopAndBottomMismatch()
{
const string initialStatus = "Parent: Top=None, Bottom=Container | Child: Top=Container, Bottom=Container";
App.WaitForElement("TopMarker");
App.WaitForElement("BottomMarker");
Assert.That(App.WaitForTextToBePresentInElement("SafeAreaStatusLabel", initialStatus), Is.True);

var root = App.WaitForElement("RootGrid").GetRect();
var rootTop = root.Y;
var rootBottom = root.Y + root.Height;
var singleTopInset = App.WaitForElement("TopMarker").GetRect().Y - rootTop;
var bottomMarker = App.WaitForElement("BottomMarker").GetRect();
var singleBottomInset = rootBottom - (bottomMarker.Y + bottomMarker.Height);
#if MACCATALYST
if (singleTopInset <= 5)
Assert.Ignore("This MacCatalyst environment does not expose a measurable title-bar safe area.");
#endif
Assert.That(singleTopInset, Is.GreaterThan(5),
"The child must apply the top safe area even though its parent handles only Bottom.");
#if !MACCATALYST
Assert.That(singleBottomInset, Is.GreaterThan(5),
"The parent must apply the bottom safe area while the child defers that edge.");
#endif

App.Tap("ToggleParentEdgeButton");
Assert.That(
App.WaitForTextToBePresentInElement(
"SafeAreaStatusLabel",
"Parent: Top=Container, Bottom=None | Child: Top=Container, Bottom=Container"),
Is.True);

App.RetryAssert(() =>
{
var parentAndChildInset = App.WaitForElement("TopMarker").GetRect().Y - rootTop;
Assert.That(parentAndChildInset, Is.EqualTo(singleTopInset).Within(3),
"When both parent and child request Top, ancestor arbitration must prevent double padding.");
});
#if !MACCATALYST
App.RetryAssert(() =>
{
var childBottomMarker = App.WaitForElement("BottomMarker").GetRect();
var childBottomInset = rootBottom - (childBottomMarker.Y + childBottomMarker.Height);
Assert.That(childBottomInset, Is.EqualTo(singleBottomInset).Within(3),
"When the parent stops handling Bottom, the child must apply that newly unblocked edge.");
});
#endif
}
}
}
#endif
1 change: 1 addition & 0 deletions src/Core/src/Handlers/View/ViewHandler.iOS.cs
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ internal static void UpdateTransformation(IViewHandler handler, IView view)

internal static void MapSafeAreaEdges(IViewHandler handler, IView view)
{
handler.ToPlatform().InvalidateSafeAreaWithDescendants();
view.InvalidateMeasure();
}
}
Expand Down
79 changes: 54 additions & 25 deletions src/Core/src/Platform/iOS/MauiScrollView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,15 @@ public class MauiScrollView : UIScrollView, IUIViewLifeCycleEvents, ICrossPlatfo
/// </summary>
bool _safeAreaInvalidated = true;

// Cached result of whether a parent MauiView is already applying safe area adjustments.
// Null means not yet determined. Invalidated when view hierarchy changes.
bool? _parentHandlesSafeArea;
// Cached per-edge (Left=0, Top=1, Right=2, Bottom=3) result of whether an ancestor
// MauiView already applies a real, non-zero safe area inset for that edge. Reused
// across layout passes to avoid re-walking the ancestor chain (and the allocation that
// walk would otherwise require) on every LayoutSubviews call. Invalidated by the same
// events that previously invalidated the whole-view _parentHandlesSafeArea cache:
// SafeAreaInsetsDidChange, InvalidateSafeArea, MovedToWindow, and ancestor
// SafeAreaEdges changes.
readonly bool[] _blockedEdgesCache = new bool[4];
bool _blockedEdgesCacheValid;

/// <summary>
/// Flag indicating whether this scroll view should apply safe area adjustments to its content.
Expand Down Expand Up @@ -127,18 +133,19 @@ bool RespondsToSafeArea()
}

/// <summary>
/// Checks if any ancestor MauiView is already applying safe area adjustments.
/// When a parent already handles safe area, this scroll view should not double-apply insets,
/// which would otherwise cause infinite layout cycles (#33595).
/// Returns this scroll view's own, already-resolved safe area component for the given edge
/// (Left=0, Top=1, Right=2, Bottom=3), used by descendants (or, in principle, callers)
/// to determine whether this view has a real, non-zero inset for a specific edge.
/// </summary>
bool IsParentHandlingSafeArea()
double GetSafeAreaComponentForEdge(int edge) => edge switch
{
if (_parentHandlesSafeArea.HasValue)
return _parentHandlesSafeArea.Value;
0 => _safeArea.Left,
1 => _safeArea.Top,
2 => _safeArea.Right,
3 => _safeArea.Bottom,
_ => 0
};

_parentHandlesSafeArea = this.FindParent(x => x is MauiView mv && mv.AppliesSafeAreaAdjustments) is not null;
return _parentHandlesSafeArea.Value;
}

/// <summary>
/// Called by iOS when the adjusted content inset changes (e.g., when safe area changes).
Expand Down Expand Up @@ -166,7 +173,7 @@ public override void SafeAreaInsetsDidChange()
{
// Note: UIKit invokes LayoutSubviews right after this method
base.SafeAreaInsetsDidChange();
_parentHandlesSafeArea = null;
_blockedEdgesCacheValid = false;
_safeAreaInvalidated = true;
}

Expand All @@ -175,7 +182,7 @@ public override void SafeAreaInsetsDidChange()
/// </summary>
internal void InvalidateSafeArea()
{
_parentHandlesSafeArea = null;
_blockedEdgesCacheValid = false;
_safeAreaInvalidated = true;
SetNeedsLayout();
}
Expand Down Expand Up @@ -203,20 +210,30 @@ SafeAreaRegions GetSafeAreaRegionForEdge(int edge)

SafeAreaEdges? _previousEdges;

UIEdgeInsets GetInset()
/// <summary>
/// Resolves the manual, per-edge inset to apply given a source set of raw insets.
/// Used both for the manual (mixed-edge) path, where <paramref name="sourceInsets"/> is
/// this view's SafeAreaInsets, and for the uniform-edge native path, where
/// <paramref name="sourceInsets"/> is <see cref="SystemAdjustedContentInset"/> — so both
/// paths get identical per-edge ancestor-blocking behavior and neither can double-apply
/// an inset a parent already handles (#33595, #32586, #34563).
/// </summary>
UIEdgeInsets GetInset(UIEdgeInsets sourceInsets)
{
var leftRegion = GetSafeAreaRegionForEdge(0);
var topRegion = GetSafeAreaRegionForEdge(1);
var rightRegion = GetSafeAreaRegionForEdge(2);
var bottomRegion = GetSafeAreaRegionForEdge(3);

var safeAreaInsets = SafeAreaInsets;
// Single ancestor walk resolves all 4 edges at once, cached until invalidated
// (see SafeAreaInsetsExtensions.ResolveParentBlockedEdges) to avoid re-walking on every layout pass.
var blockedEdges = this.ResolveParentBlockedEdges(_blockedEdgesCache, ref _blockedEdgesCacheValid);

var manualInset = new UIEdgeInsets(
top: GetManualInsetForEdge(topRegion, safeAreaInsets.Top),
left: GetManualInsetForEdge(leftRegion, safeAreaInsets.Left),
bottom: GetManualInsetForEdge(bottomRegion, safeAreaInsets.Bottom),
right: GetManualInsetForEdge(rightRegion, safeAreaInsets.Right)
top: GetManualInsetForEdge(topRegion, sourceInsets.Top, blockedEdges[1]),
left: GetManualInsetForEdge(leftRegion, sourceInsets.Left, blockedEdges[0]),
bottom: GetManualInsetForEdge(bottomRegion, sourceInsets.Bottom, blockedEdges[3]),
right: GetManualInsetForEdge(rightRegion, sourceInsets.Right, blockedEdges[2])
);

return manualInset;
Expand Down Expand Up @@ -263,12 +280,19 @@ _ when SafeAreaEdges.IsSoftInput(region) => UIScrollViewContentInsetAdjustmentBe
return true;
}

static nfloat GetManualInsetForEdge(SafeAreaRegions safeAreaRegion, nfloat safeAreaInset)
static nfloat GetManualInsetForEdge(SafeAreaRegions safeAreaRegion, nfloat safeAreaInset, bool isEdgeBlockedByParent)
{
// Edge-to-edge content - no safe area padding
if (safeAreaRegion == SafeAreaRegions.None)
return 0;

// If an ancestor already applies a real, non-zero safe area inset for this exact
// edge, defer to it and don't double-apply here (#33595, #32586). Edges are checked
// independently, so a parent handling only Top never blocks this scroll view from
// independently handling Bottom (#28986, #34563).
if (isEdgeBlockedByParent)
return 0;

return safeAreaInset;
}

Expand Down Expand Up @@ -388,12 +412,17 @@ bool ValidateSafeArea()
// This can result in a loop of invalidations as the layout toggles between these states.
// To prevent this, we ignore safe area calculations on child views when they are inside a scroll view.
if (SystemAdjustedContentInset == UIEdgeInsets.Zero || ContentInsetAdjustmentBehavior == UIScrollViewContentInsetAdjustmentBehavior.Never)
_safeArea = GetInset().ToSafeAreaInsets();
_safeArea = GetInset(SafeAreaInsets).ToSafeAreaInsets();
else
_safeArea = SystemAdjustedContentInset.ToSafeAreaInsets();
_safeArea = GetInset(SystemAdjustedContentInset).ToSafeAreaInsets();

var oldApplyingSafeAreaAdjustments = _appliesSafeAreaAdjustments;
_appliesSafeAreaAdjustments = !IsParentHandlingSafeArea() && RespondsToSafeArea() && !_safeArea.IsEmpty;
// Parent-edge blocking is now resolved per-edge inline while computing GetInset() above
// (see ResolveParentBlockedEdges/GetManualInsetForEdge) for BOTH the manual (mixed-edge)
// path and the uniform-edge native path (SystemAdjustedContentInset), so _safeArea
// already reflects the net, post-ancestor-arbitration state either way — no separate
// whole-view parent check is needed.
_appliesSafeAreaAdjustments = RespondsToSafeArea() && !_safeArea.IsEmpty;

if (_systemAdjustedContentInset != SystemAdjustedContentInset)
{
Expand Down Expand Up @@ -714,7 +743,7 @@ public override void MovedToWindow()

// Clear cached scroll view descendant status since the view hierarchy may have changed
_scrollViewDescendant = null;
_parentHandlesSafeArea = null;
_blockedEdgesCacheValid = false;

// Mark safe area as invalidated since moving to a new window may change safe area
_safeAreaInvalidated = true;
Expand Down
Loading
Loading