如何在MAUI中获取Tabbar与Shell Navbar高度?已实现自定义ShellRenderer
在MAUI中获取Shell导航栏与标签栏高度的方案
安卓平台(自定义ShellRenderer)
在已实现的ShellRenderer中,可通过原生控件引用直接获取Shell导航栏(Toolbar)和标签栏(BottomNavigationView)的高度,代码如下:
protected override void OnElementSet(Shell shell) { base.OnElementSet(shell); // 获取Shell顶部导航栏(Toolbar)高度,转换为DP var toolbar = FindViewById<AndroidX.AppCompat.Widget.Toolbar>(Resource.Id.toolbar); if (toolbar != null) { double shellNavbarHeight = toolbar.Height / DeviceDisplay.Current.MainDisplayInfo.Density; } // 获取Shell底部标签栏(BottomNavigationView)高度,转换为DP var bottomNav = FindViewById<Google.Android.Material.BottomNavigation.BottomNavigationView>(Resource.Id.bottom_navigation); if (bottomNav != null) { double shellTabbarHeight = bottomNav.Height / DeviceDisplay.Current.MainDisplayInfo.Density; } // 你原有获取系统导航栏、状态栏高度的代码 int resourceId = Resources.GetIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId > 0) { int systemNavBarHeight = Resources.GetDimensionPixelSize(resourceId) / DeviceDisplay.Current.MainDisplayInfo.Density; } resourceId = Resources.GetIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { int statusBarHeight = Resources.GetDimensionPixelSize(resourceId) / DeviceDisplay.Current.MainDisplayInfo.Density; } }
iOS平台(自定义ShellRenderer)
iOS端需通过Shell对应的原生控制器组件获取高度,同时适配刘海屏的安全区域:
protected override void OnElementSet(Shell shell) { base.OnElementSet(shell); // 获取Shell顶部导航栏高度(含顶部安全区域) if (ViewController?.NavigationController?.NavigationBar != null) { double shellNavbarHeight = ViewController.NavigationController.NavigationBar.Frame.Height + UIApplication.SharedApplication.Delegate.GetWindow().SafeAreaInsets.Top; } // 获取Shell底部标签栏高度(含底部安全区域) if (ViewController?.TabBarController?.TabBar != null) { double shellTabbarHeight = ViewController.TabBarController.TabBar.Frame.Height + UIApplication.SharedApplication.Delegate.GetWindow().SafeAreaInsets.Bottom; } }
注意事项
- 若首次获取高度为0,可尝试在
ViewDidAppear(iOS)或OnWindowAttached(安卓)等控件初始化完成后的生命周期方法中延迟获取。 - 统一使用
DeviceDisplay.Current.MainDisplayInfo.Density将原生像素转换为与设备无关的DP,保证跨设备尺寸一致性。
内容的提问来源于stack exchange,提问作者Darren Fillis
相关产品推荐
相关产品推荐

