Pxaml
Pxaml

Reputation: 553

Xamarin Forms IOS 13 UIUserInterfaceStyle -Dark Mode

How can I make my app responsive with this "NEW FEATURE" . I want to have an only light mode for now. I saw this

UIUserInterfaceStyle style = UIUserInterfaceStyle.Light;

How to activate this on my Xamarin Forms app

Upvotes: 2

Views: 2153

Answers (2)

hnabbasi
hnabbasi

Reputation: 191

You can react to mode changes by following the previous comment. If you want to set the mode inside your app, you can do so by setting Window.OverrideUserInterfaceStyle in your AppDelegate.cs for instance,

Window.OverrideUserInterfaceStyle = UIUserInterfaceStyle.Dark;

Here is the full blog post on how to support dark mode in Xamarin.Forms, https://intelliabb.com/2019/11/02/how-to-support-dark-mode-in-xamarin-forms/

Upvotes: 0

Juan Manuel Gentili
Juan Manuel Gentili

Reputation: 163

You can react to changes in the user interface style by creating two resources: LightTheme and DarkTheme (they will be ResourceDictionaries). Inside them, you can add custom colors. For example:

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>

Then, you have to create a CustomRenderer for the ContentPage element (of course, only for 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.

Upvotes: 2

Related Questions