.NET MAUI iOS应用:浅色主题下设置状态栏文字为白色的方法
.NET MAUI iOS浅色模式下设置状态栏文字为白色的操作步骤
1. 配置Info.plist开启自定义状态栏权限
在项目的Platforms/iOS/Info.plist文件中添加以下配置,允许通过视图控制器控制状态栏样式:
<key>UIViewControllerBasedStatusBarAppearance</key> <true/>
2. 创建自定义导航渲染器(针对导航页面场景)
如果应用使用NavigationPage,在Platforms/iOS目录下新建CustomNavigationRenderer.cs,代码如下:
using Microsoft.Maui.Controls.Handlers.Compatibility; using UIKit; namespace YourAppNamespace.Platforms.iOS; public class CustomNavigationRenderer : NavigationRenderer { protected override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); if (UIDevice.CurrentDevice.CheckSystemVersion(13, 0)) { // 导航栏设为黑色样式,配合状态栏白色文字 NavigationController.NavigationBar.BarStyle = UIBarStyle.Black; SetNeedsStatusBarAppearanceUpdate(); } else { // iOS13以下直接设置状态栏样式 UIApplication.SharedApplication.SetStatusBarStyle(UIStatusBarStyle.LightContent, false); } } // 重写方法指定状态栏文字样式 public override UIStatusBarStyle PreferredStatusBarStyle() { return UIStatusBarStyle.LightContent; } }
3. 注册自定义渲染器
在项目根目录的MauiProgram.cs中,注册上述导航渲染器:
using YourAppNamespace.Platforms.iOS; var builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() // 其他项目配置... .ConfigureMauiHandlers(handlers => { #if IOS handlers.AddHandler<NavigationPage, CustomNavigationRenderer>(); #endif });
4. 动态监听主题切换(可选)
如果需要在用户切换系统主题时自动适配,在AppDelegate.cs中添加主题变化监听:
public override void TraitCollectionDidChange(UITraitCollection previousTraitCollection) { base.TraitCollectionDidChange(previousTraitCollection); // 检测切换到浅色模式时更新状态栏样式 if (TraitCollection.UserInterfaceStyle == UIUserInterfaceStyle.Light) { UIApplication.SharedApplication.SetStatusBarStyle(UIStatusBarStyle.LightContent, true); if (Window?.RootViewController is UINavigationController navController) { navController.NavigationBar.BarStyle = UIBarStyle.Black; } } }
内容的提问来源于stack exchange,提问作者Virang Patel
相关产品推荐
相关产品推荐

