【问题标题】:SwiftUI: The compiler is unable to type-check this expression in reasonable timeSwiftUI:编译器无法在合理的时间内对该表达式进行类型检查
【发布时间】:2021-10-26 07:23:45
【问题描述】:

我想从 EKEvent 获取日历颜色。但我得到了错误: 编译器无法在合理的时间内对该表达式进行类型检查;尝试将表达式分解为不同的子表达式 Rectangle().fill 导致错误。 如何从 calendar.cgcolor 中获取 Rectangle 的 UIColor?

           ForEach(0..<data.eventsByDay.prefix(4).count)
            {(section) in
              
                HStack(alignment: .bottom){
                    ForEach(0..<data.eventsByDay[section].prefix(3).count)
                    {(row) in
                        
                        Rectangle().fill(UIColor(cgcgolor: data.eventsByDay[section][row].calendar.cgcolor))
                        .frame(width: 3, height: 26, alignment: .leading)
                        .cornerRadius(1.5)
                        .padding(.bottom, 1.0)
                    }
             }

【问题讨论】:

    标签: swiftui uicolor cgcolor


    【解决方案1】:

    当 Xcode 无法确定错误的确切原因时会发生此错误。

    我建议你从错误中得到以下指令

    尝试将表达式分解为不同的子表达式

    您可以通过将部分视图移动到单独的函数或View 中来做到这一点,但您也可以逐个注释掉块,直到您看到实际错误或直到它构建:在这种情况下,错误是在注释行之一上。


    在他的情况下,您可以注释掉ForEachs 并用常量替换它们:

    //ForEach(0..<data.eventsByDay.prefix(4).count)
    //{(section) in
        let section = 0
        HStack(alignment: .bottom){
    //        ForEach(0..<data.eventsByDay[section].prefix(3).count)
    //        {(row) in
                let row = 0
                Rectangle().fill(UIColor(cgcgolor: data.eventsByDay[section][row].calendar.cgcolor))
                    .frame(width: 3, height: 26, alignment: .leading)
                    .cornerRadius(1.5)
                    .padding(.bottom, 1.0)
            }
        }
    }
    

    然后 Xcode 将能够告诉您,您在 UIColor 初始化程序中输入了拼写错误(cgColor 而不是 cgcgolor),并且 fill 使用 Color 而不是 UIColor -第二个来自UIKit,使用 SwiftUI 几乎永远不需要它。

    所以固定的变体看起来像:

    ForEach(0..<data.eventsByDay.prefix(4).count)
    {(section) in
        let section = 0
        HStack(alignment: .bottom){
            ForEach(0..<data.eventsByDay[section].prefix(3).count)
            {(row) in
                let row = 0
                Rectangle().fill(Color(data.eventsByDay[section][row].calendar.cgcolor))
                    .frame(width: 3, height: 26, alignment: .leading)
                    .cornerRadius(1.5)
                    .padding(.bottom, 1.0)
            }
        }
    }
    

    【讨论】:

    • With -> Rectangle().fill(Color it works。我之前用 cgColor 试过,但不知道用 Color 代替 UIColor ...完美,非常感谢!
    猜你喜欢
    • 2020-06-30
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    相关资源
    最近更新 更多