我正试图在我的iOS应用程序中实现暗色模式。我需要使用命名颜色来实现这个目标,但是遇到了一些问题。在iOS 13模拟器上在浅色和暗色模式之间切换时一切正常,并且iOS 12模拟器中的颜色也是正确的。问题出现在我尝试在iOS 11模拟器上运行应用程序时。任何我在Storyboard中使用的命名颜色都会默认为该颜色的暗模式,在代码中访问一个命名颜色时,我得到nil值。只是想知道是否有其他人遇到过这个问题。
我正试图在我的iOS应用程序中实现暗色模式。我需要使用命名颜色来实现这个目标,但是遇到了一些问题。在iOS 13模拟器上在浅色和暗色模式之间切换时一切正常,并且iOS 12模拟器中的颜色也是正确的。问题出现在我尝试在iOS 11模拟器上运行应用程序时。任何我在Storyboard中使用的命名颜色都会默认为该颜色的暗模式,在代码中访问一个命名颜色时,我得到nil值。只是想知道是否有其他人遇到过这个问题。
这是Xcode 11与IOS 11中的一个漏洞,存在两个与IOS 11中具名颜色相关的问题。
UIColor
初始化方法init?(named name: String)
在IOS 11中返回nil
以下是临时解决方案,直到在即将发布的Xcode更新版本中修复此问题。
If UIColor
init method init?(named name: String)
returns nil
you need to provide fallback color for light mode.
let color = UIColor(named: "myColor") ?? UIColor.black // default color for IOS 11
Named color issue for Story board and xib files, if you observe the changes in your xib file or storyboard after setting any name color you will notice there is a namedColor
xml tag under resources
tab. And for each namedColor
there is fallback color there, that fallback color is being in IOS 11 case because named color isn't working. You can even see the warings in your console.
<resources>
<namedColor name="NavigationBar">
<color red="0.2669999897480011" green="0.70999997854232788" blue="0.046999998390674591" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
</namedColor>
</resources>
Bug in Xcode 11 is that default value is set to dark mode version if your MacOS
appearance is set to Dark
and it picks light
color version for default values if your MacOS
appearance is set to Light
. Workarounds to fix this for IOS 11.
MacOS
appearance to Light
. After that you need to open each and every storyboards or xib files in yours project once. Once you open it, editor will automatically pick the Light
version of your colors and you can see in your source control that file is modified and default value will be Light
version of your color asset. Note that every time your change any value in your color assets, you have to do this again for all the xib files using that named color. 看起来苹果公司已经知道这个问题了。
引用自https://developer.apple.com/ios/submit/
请注意,使用命名颜色构建的Xcode 11应用程序在iOS 11或更早版本上运行时可能会出现查找失败(未返回任何值)的情况。这将在未来的Xcode更新中得到修复。为了避免此问题,请将最低部署目标提高到iOS 12或更高版本以立即提交到App Store,或在下一个Xcode GM候选种子可用时重新构建。
更新20190917
使用包括iOS 13、iPadOS、watchOS 6、tvOS 12和macOS Catalina的SDK构建您的应用程序,其中包括Xcode 11 GM种子2。从2020年4月开始,所有提交到App Store的iOS应用程序都需要使用iOS 13 SDK或更高版本构建。它们还必须支持iPhone XS Max或12.9英寸iPad Pro(第3代)或更高版本的全屏设计。
看起来问题出在苹果这边。即使是Xcode 11 GM seed也有这个问题。人们正在苹果开发者论坛上讨论这个问题。
UIColor(named: "systemBlue") ?? UIColor.blue