Xamarin Forms IOS 13 UIUserInterfaceStyle-黑暗模式

时间:2019-09-25 13:28:50

标签: xamarin.forms xamarin.ios ios13 ios-darkmode

如何使用此“新功能”使我的应用程序响应。我现在想要一个唯一的灯光模式。 我看到了

UIUserInterfaceStyle style = UIUserInterfaceStyle.Light;

如何在我的Xamarin Forms应用程序上激活它

2 个答案:

答案 0 :(得分:2)

您可以通过创建两个资源来应对用户界面样式的更改:LightTheme和DarkTheme(它们将是ResourceDictionaries)。在其中,您可以添加自定义颜色。例如:

LightTheme.xaml:

<ResourceDictionary
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="DarkMode.Styles.LightTheme">

    <Color x:Key="background">#FFFFFF</Color>
    <Color x:Key="mainLabel">#000000</Color>

</ResourceDictionary>

DarkTheme.xaml:

<ResourceDictionary
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="DarkMode.Styles.DarkTheme">

    <Color x:Key="background">#000000</Color>
    <Color x:Key="mainLabel">#FFFFFF</Color>

</ResourceDictionary>

然后,您必须为ContentPage元素创建一个CustomRenderer(当然,仅适用于iOS):

[assembly: ExportRenderer(typeof(ContentPage), typeof([YOUR_NAMESPACE].iOS.Renderers.PageRenderer))]
namespace [YOUR_NAMESPACE].iOS.Renderers
{
  public class PageRenderer : Xamarin.Forms.Platform.iOS.PageRenderer
  {
    protected override void OnElementChanged(VisualElementChangedEventArgs e)
    {
      base.OnElementChanged(e);

      if (e.OldElement != null || Element == null)
          return;

      try
      {
          SetTheme();
      }
      catch(Exception ex)
      {

      }
    }

    public override void TraitCollectionDidChange(UITraitCollection previousTraitCollection)
    {
        base.TraitCollectionDidChange(previousTraitCollection);

        if (TraitCollection.UserInterfaceStyle != previousTraitCollection.UserInterfaceStyle)
            SetTheme();
    }

    private void SetTheme()
    {
        if (TraitCollection.UserInterfaceStyle == UIUserInterfaceStyle.Dark)
            App.Current.Resources = new DarkTheme();
        else
            App.Current.Resources = new LightTheme();
    }
  }
}

More information

答案 1 :(得分:0)

您可以按照上一条注释对模式更改做出反应。如果您想在应用程序内部设置模式,可以通过在Window.OverrideUserInterfaceStyle中设置AppDelegate.cs来实现,

Window.OverrideUserInterfaceStyle = UIUserInterfaceStyle.Dark;

此处是有关如何在Xamarin.Forms中支持暗模式的完整博客文章, https://intelliabb.com/2019/11/02/how-to-support-dark-mode-in-xamarin-forms/