【问题标题】:SwiftUI custom accentColor not working on physical device(iOS 13) but works everywhere else(iOS 14.0+)SwiftUI 自定义的accentColor 不适用于物理设备(iOS 13)但适用于其他任何地方(iOS 14.0+)
【发布时间】:2021-01-28 16:57:24
【问题描述】:

在我的 SwiftUI View 我有一个 Image 我从资产加载。我已将foregroundColor 设置为accentColor,我还在资产中将其设置为我的自定义AccentColor,它将在整个应用程序中使用。

资产:

内容视图正文:

var body: some View {
    Image("MyImageName")
        .resizable()
        .renderingMode(.template)
        .foregroundColor(.accentColor)
        .frame(width: 32, height: 32, alignment: .center)
}

预览和模拟器在右侧显示图像foregroundColor。但是,在物理设备上运行时,foregroundColor 不知何故仍然是手机的默认蓝色accentColor

预览:

模拟器:

真机:

为什么会这样?以及如何确保 AssentColor 跨设备工作,无论 iOS 版本如何,而无需修改 iPhone 上的任何设置?调试详情:设备iOS版本为iOS 13.5.1和Xcode 12.0.1。

【问题讨论】:

  • .accentColor 已在系统中定义。您究竟是如何以及在何处尝试重新定义它的?最后,为什么不直接将 foregroundColor 设置为资产颜色?
  • 检查我在 OP 中指定的 Xcode 和 iOS 的版本。您会发现.accentColor 在真实设备上的工作方式不如在模拟器上的预期效果。

标签: swift image colors swiftui assets


【解决方案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))
        }
    }
}

【讨论】:

    【解决方案2】:

    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")
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多