How to allow for iOS status bar and iPhone X notch in Xamarin.Forms

后端 未结 3 897
心在旅途
心在旅途 2021-01-02 19:48

I\'m fairly new to this, so sorry if this is a dumb question. How do I get my Xamarin.Forms app to start below the status bar or the notch when applicable? I\'ve tried using

3条回答
  •  温柔的废话
    2021-01-02 20:27

    You'll need to consider the safe area but have the background colors expand to take the full screen. So you shouldn't use

    On().SetUseSafeArea(true);
    

    this will box your page with large empty spaces on the bottom and top edges.

    Instead, you should measure the safe areas and apply it as padding to your root view.

    [assembly: ResolutionGroupName("Enterprise")]
    [assembly: ExportEffect(typeof(SafeAreaPaddingEffect), nameof(SafeAreaPaddingEffect))]
    namespace Enterprise.iOS.Effects
    {
        class SafeAreaPaddingEffect : PlatformEffect
        {
            Thickness _padding;
            protected override void OnAttached()
            {
                if (Element is Layout element)
                {
                    if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
                    {
                        _padding = element.Padding;
                        var insets = UIApplication.SharedApplication.Windows[0].SafeAreaInsets; // Can't use KeyWindow this early
                        if (insets.Top > 0) // We have a notch
                        {
                            element.Padding = new Thickness(_padding.Left + insets.Left, _padding.Top + insets.Top, _padding.Right + insets.Right, _padding.Bottom);
                            return;
                        }
                    }
                    // Uses a default Padding of 20. Could use an property to modify if you wanted.
                    element.Padding = new Thickness(_padding.Left, _padding.Top + 20, _padding.Right, _padding.Bottom);
                }
            }
    
            protected override void OnDetached()
            {
                if (Element is Layout element)
                {
                    element.Padding = _padding;
                }
            }
        }
    }
    

    then in xaml:

            
                              
                           
                                
                            
                        
                            
                                    
                                    
                                
                                    
        
    
    

    ref: https://xamarinhelp.com/safeareainsets-xamarin-forms-ios/ Thank Adam, not me!

提交回复
热议问题