如何使用.NET MAUI平台特定代码设置iOS的状态栏颜色?

3

我想在.NET MAUI上设置iOS的状态栏颜色。我尝试了社区工具包(当前存在一个问题,即Android的发布版本启动时会崩溃),背景颜色和背景(都无法在iOS启动时生效),以及在状态栏后面绘制的形状上设置颜色,但效果不太好,因为设备方向有点麻烦。我尝试过搜索如何使用UIKit设置颜色,但没有找到太多有用的信息。任何帮助都将不胜感激。

4个回答

6

您可以使用.NET MAUI CommunityToolkit包来设置iOS状态栏颜色

XAML用法:

为了在XAML中使用工具包,您可以使用此命名空间:

xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"

然后在您的XAML页面中添加以下内容:

 <ContentPage.Behaviors> 
        <toolkit:StatusBarBehavior StatusBarColor="Red" StatusBarStyle="LightContent"> 
        </toolkit:StatusBarBehavior>
 </ContentPage.Behaviors>


1
这个很好用,谢谢。我只需要更改Android的默认颜色。 - JakenBake

2
我所知道的最简单的方法是重写finishedLaunching方法并更改颜色:
 public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
    {
        UIView statusBar = UIApplication.SharedApplication.ValueForKey(new NSString("statusBar")) as UIView;
        if (statusBar != null && statusBar.RespondsToSelector(new ObjCRuntime.Selector("setBackgroundColor:")))
        {
            statusBar.BackgroundColor =UIColor.Yellow;
        }
        return base.FinishedLaunching(application, launchOptions);
    }

在你的 info.plist 文件中,你需要设置以下内容:
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>

这个方法可行,最终采用了 iOS 特定的工具包路径。感谢您的洞察力。 - JakenBake

0

在共享的顶层文件App.xaml中更改PageBackgroundColor键


这行代码:<Color x:Key="PageBackgroundColor">White</Color>

<?xml version="1.0" encoding="UTF-8"?>

<Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiBlazorApp.App">
    <Application.Resources>
        <ResourceDictionary>

            <!-- HERE! -->
            <Color x:Key="PageBackgroundColor">White</Color>
            <Color x:Key="PrimaryTextColor">Black</Color>

            <Style TargetType="Label">
                <Setter Property="TextColor" Value="{DynamicResource PrimaryTextColor}" />
                <Setter Property="FontFamily" Value="OpenSansRegular" />
            </Style>

            <Style TargetType="Button">
                <Setter Property="TextColor" Value="{DynamicResource PrimaryTextColor}" />
                <Setter Property="FontFamily" Value="OpenSansRegular" />
                <Setter Property="BackgroundColor" Value="#2b0b98" />
                <Setter Property="Padding" Value="14,10" />
            </Style>

        </ResourceDictionary>
    </Application.Resources>
</Application>

-1
在 .NET MAUI 中,如果要使用平台特定的代码为 iOS 设置状态栏颜色,则可以使用 StatusBar 类。
示例代码如下:
using Xamarin.Forms; 
using Xamarin.Forms.PlatformConfiguration.iOSSpecific;

// ...

var statusBar = new StatusBar();

statusBar.GetForCurrentView().BackgroundColor = Colors.Red;

2
.NET MAUI很遗憾不能使用Xamarin命名空间。不过还是感谢您的尝试。 - JakenBake

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接