Search code examples
xamarin.formsxamarin.iossafearea

SafeAreaInsets are 0 when View.OnAppearing gets triggered


I am doing some manual positioning and need to take into account the safearea on ios.

The problem I have is that when I am in my OnAppearing method, the SafeAreaInserts method returns thickness values of 0. After rotating the device (in the SizeChanged event) this is no longer the case. Since SizeChanged does not get triggered when entering the view, I can't find the event that is raised when the SafeAreaInsets are set.

var safeInsets = On().SafeAreaInsets();

In this topic I found that the event for a changed SafeAreaInsert gets triggered "a fraction later" but I don't seem to have this event available in my shared Xamarin.Forms project.


Solution

  • For the ViewSafeAreaInsetsDidChange method, it gets called from the PageRenderer. You could override the default iOS PageRenderer and hook up to the ViewSafeAreaInsetsDidChange override.

        public override void ViewSafeAreaInsetsDidChange()
        {
    
            var page = (Element as Page);
            if (page != null && Forms.IsiOS11OrNewer)
            {
                var insets = NativeView.SafeAreaInsets;
                if(page.Parent is TabbedPage)
                {
                    insets.Bottom = 0;
                }
                page.On<PlatformConfiguration.iOS>().SetSafeAreaInsets(new Thickness(insets.Left, insets.Top, insets.Right, insets.Bottom));
            
            }
            base.ViewSafeAreaInsetsDidChange();
        }
    

    With more details, you could check the link below. https://github.com/xamarin/Xamarin.Forms/blob/4d49e5786a4c9cfc6eea00bbaa5b57bc09679186/Xamarin.Forms.Platform.iOS/Renderers/PageRenderer.cs