SwiftUI 自定义 accentColor 不适用于物理设备(iOS 13)但适用于其他任何地方(iOS 14.0+)
SwiftUI custom accentColor not working on physical device(iOS 13) but works everywhere else(iOS 14.0+)
在我的 SwiftUI View
中,我有一个从资产中加载的 Image
。我已将 foregroundColor
设置为 accentColor
,我还在资产中将其设置为我的自定义 AccentColor
,它将在整个应用程序中使用。
资产:
ContentView 主体:
var body: some View {
Image("MyImageName")
.resizable()
.renderingMode(.template)
.foregroundColor(.accentColor)
.frame(width: 32, height: 32, alignment: .center)
}
预览和模拟器显示右图foregroundColor
。但是,虽然 运行 在物理设备上 foregroundColor
不知何故仍然是 phone.
的默认蓝色 accentColor
预览:
模拟器:
真实设备:
为什么会这样?以及如何在不修改 iPhone 上的任何设置的情况下确保 AssentColor
跨设备工作,无论 iOS 版本如何?调试详情:设备 iOS 版本为 iOS 13.5.1 和 Xcode 12.0.1.
因此,在进一步测试时我发现即使 accentColor
可从 iOS 13.0
获得,自定义 accentColor
仅可从 iOS 14.0
获得。因此,我创建了一个扩展以在 iOS 13
中手动使用资产中的 accentColor
,并在 iOS 14.0
及更高版本中正常工作。
extension Color {
static var accent: Color {
if #available(iOS 14.0, *) {
return accentColor
} else {
return Color(#colorLiteral(red: 0.5, green: 0.5, blue: 0.5, alpha: 1))
}
}
}
Color.accentColor
工作正常,即使在 View
和 .accentColor(newColor)
上更改它也适用于 iOS 13.
唯一的问题是 iOS 13 没有将 Color.accentColor
设置为 ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME
指定的资产中的颜色。
对我有用的是通过简单地将 window.tintColor
设置为该颜色来手动执行该步骤:
if #available(iOS 14, *) {} else {
window.tintColor = UIColor(named: "AccentColor")
}
我想在这里提醒一下,可以通过访问应用程序的属性(包括选择颜色、色调颜色等)或在应用程序创建第一个 UIWindow 之前构建一些视图来破坏全局应用程序色调颜色。
如果色调颜色在任何地方(包括在模拟器中)都被破坏,请确保您在第一个 window 之前没有尝试构建或访问 UIKit 组件,包括第三方 SDK。在我的应用中,third-party 崩溃日志记录 SDK 破坏了强调色。
在我的 SwiftUI View
中,我有一个从资产中加载的 Image
。我已将 foregroundColor
设置为 accentColor
,我还在资产中将其设置为我的自定义 AccentColor
,它将在整个应用程序中使用。
资产:
ContentView 主体:
var body: some View {
Image("MyImageName")
.resizable()
.renderingMode(.template)
.foregroundColor(.accentColor)
.frame(width: 32, height: 32, alignment: .center)
}
预览和模拟器显示右图foregroundColor
。但是,虽然 运行 在物理设备上 foregroundColor
不知何故仍然是 phone.
accentColor
预览:
模拟器:
真实设备:
为什么会这样?以及如何在不修改 iPhone 上的任何设置的情况下确保 AssentColor
跨设备工作,无论 iOS 版本如何?调试详情:设备 iOS 版本为 iOS 13.5.1 和 Xcode 12.0.1.
因此,在进一步测试时我发现即使 accentColor
可从 iOS 13.0
获得,自定义 accentColor
仅可从 iOS 14.0
获得。因此,我创建了一个扩展以在 iOS 13
中手动使用资产中的 accentColor
,并在 iOS 14.0
及更高版本中正常工作。
extension Color {
static var accent: Color {
if #available(iOS 14.0, *) {
return accentColor
} else {
return Color(#colorLiteral(red: 0.5, green: 0.5, blue: 0.5, alpha: 1))
}
}
}
Color.accentColor
工作正常,即使在 View
和 .accentColor(newColor)
上更改它也适用于 iOS 13.
唯一的问题是 iOS 13 没有将 Color.accentColor
设置为 ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME
指定的资产中的颜色。
对我有用的是通过简单地将 window.tintColor
设置为该颜色来手动执行该步骤:
if #available(iOS 14, *) {} else {
window.tintColor = UIColor(named: "AccentColor")
}
我想在这里提醒一下,可以通过访问应用程序的属性(包括选择颜色、色调颜色等)或在应用程序创建第一个 UIWindow 之前构建一些视图来破坏全局应用程序色调颜色。
如果色调颜色在任何地方(包括在模拟器中)都被破坏,请确保您在第一个 window 之前没有尝试构建或访问 UIKit 组件,包括第三方 SDK。在我的应用中,third-party 崩溃日志记录 SDK 破坏了强调色。