From 94fea182d6cf19e96a8a87760017bd69ad0a9e0c Mon Sep 17 00:00:00 2001 From: Alan Hughes Date: Wed, 13 Sep 2023 04:39:22 -0700 Subject: [PATCH] fix: return the correct default trait collection (#38214) Summary: Currently, when the `_currentColorScheme` is nil the default comes from `[UITraitCollection currentTraitCollection]` which provides the trait collection of the context it was called in. Generally, this will work but in some cases the context can be different and this will return the wrong value also if the `Appearance` property is set in the plist, then initially that value is returned, regardless of if you have overridden it. Seen as the `userInterfaceStyle` of the window is overridden when the value is changed, then the default should be whatever the current style of the window is and not dependent on the calling context.
BeforeAfter
## Changelog: [IOS] [FIXED] - Fix the default trait collection to always return the value of the window Pull Request resolved: https://github.com/facebook/react-native/pull/38214 Test Plan: Tested on rn-tester and verified the current behaviour is unaffected and also in our own repo to make sure it addresses the problem. Video provided above Reviewed By: dmytrorykun Differential Revision: D49186069 Pulled By: cipolleschi fbshipit-source-id: f069fea8918fe17c53429564ed2a52e316ce893b --- .../react-native/React/CoreModules/RCTAppearance.mm | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/react-native/React/CoreModules/RCTAppearance.mm b/packages/react-native/React/CoreModules/RCTAppearance.mm index 2930401fc98f6e..09fc70ca9797e7 100644 --- a/packages/react-native/React/CoreModules/RCTAppearance.mm +++ b/packages/react-native/React/CoreModules/RCTAppearance.mm @@ -36,6 +36,15 @@ void RCTOverrideAppearancePreference(NSString *const colorSchemeOverride) return sColorSchemeOverride; } +static UITraitCollection *getKeyWindowTraitCollection() +{ + __block UITraitCollection *traitCollection = nil; + RCTExecuteOnMainQueue(^{ + traitCollection = RCTSharedApplication().delegate.window.traitCollection; + }); + return traitCollection; +} + NSString *RCTColorSchemePreference(UITraitCollection *traitCollection) { static NSDictionary *appearances; @@ -57,7 +66,7 @@ void RCTOverrideAppearancePreference(NSString *const colorSchemeOverride) return RCTAppearanceColorSchemeLight; } - traitCollection = traitCollection ?: [UITraitCollection currentTraitCollection]; + traitCollection = traitCollection ?: getKeyWindowTraitCollection(); return appearances[@(traitCollection.userInterfaceStyle)] ?: RCTAppearanceColorSchemeLight; // Default to light on older OS version - same behavior as Android.