首页 > 解决方案 > SwiftUI 崩溃预览中具有资产目录颜色的颜色扩展

问题描述

下面的示例在模拟器/设备中编译并运行良好,但在画布预览中遇到问题。(我试过清除缓存和派生数据)

extension Color {
  static let primary = Color("primary")
  static let test = Color(red: 1, green: 0, blue: 0)
}

这在画布预览中效果很好:

Text("hi").background(Color.test)

但是颜色资源崩溃预览:

Text("hi").background(Color.primary)


Compiling failed: cannot convert return expression of type 'AnyView' to return type 'some View'

(另外作为旁注,这似乎工作得很好Text("hi").background(Color("primary"))

标签: swiftswiftui

解决方案


有 SwiftUI 标准Color.primary(见下文),所以我认为问题是由于模棱两可造成的。

@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
extension Color {

    /// A set of colors that are used by system elements and applications.
    public static let clear: Color

   ...

   public static let primary: Color      // << here !!

为您的自定义颜色使用唯一的静态变量名称,例如

extension Color {
  static let myPrimary = Color("primary")               // << here !!
  static let test = Color(red: 1, green: 0, blue: 0)
}

使用 Xcode 11.4 测试


推荐阅读