【问题标题】:Breaking up the expression into distinct sub-expressions in a ForEach/ZStack (SwiftUI)在 ForEach/ZStack (SwiftUI) 中将表达式分解为不同的子表达式
【发布时间】:2019-11-02 19:30:36
【问题描述】:

我在最新的 SwiftUI 上有一个小问题,错误是“编译器无法在合理的时间内对该表达式进行类型检查;尝试将表达式分解为不同的子表达式”

我的代码是这样的:

let cards = ["Azertyuiop", "Bzertyuiop", "Czertyuiop", "Dzertyuiop", "Ezertyuiop", "Fzertyuiop", "Gzertyuiop", "Hzertyuiop", "Izertyuiop", "Jzertyuiop", "Kzertyuiop", "Lzertyuiop", "Bzertyuiop", "Czertyuiop", "Dzertyuiop", "Ezertyuiop", "Fzertyuiop", "Gzertyuiop", "Lzertyuiop", "Bzertyuiop", "Czertyuiop", "Dzertyuiop", "Ezertyuiop", "Fzertyuiop", "Gzertyuiop", "Lzertyuiop", "Bzertyuiop", "Czertyuiop", "Dzertyuiop", "Ezertyuiop", "Fzertyuiop", "Gzertyuiop"]
   var body: some View {
       ScrollView{
         VStack (spacing: 0, content: {
           ForEach(0..<cards.count/3) { row in // create number of rows
               HStack (spacing: 0, content: {
                   ForEach(0..<3) { column in // create 3 columns
                     ZStack(alignment: .bottomLeading){
                        Image("ghost").resizable().aspectRatio(contentMode: .fill)
                           .overlay(Rectangle().fill (LinearGradient(gradient: Gradient(colors: [.clear, .black]),startPoint: .center, endPoint: .bottom)).clipped())
                        Text(self.cards[row * 3 + column]) // this cause the error
                           .fontWeight(.semibold)
                     }
                   }
               })
            }
         })
       }
   }

我猜错误来自:row * 3 + column

所以我尝试用整数 1 代替这个计算,结果成功了。 如何在我的身体和视图中进行此计算?因为 SwiftUI 不允许我显示“预期模式”

非常感谢!

【问题讨论】:

  • 我运行你的代码,我没有收到任何错误,所以,尝试清理构建文件夹或更新到最新的 Xcode 版本

标签: swift xcode swiftui


【解决方案1】:

有两个问题。一种是使用ZStack with overlay,另一种是Linear Gradient是一个view,可以直接使用。

 ZStack(alignment: .bottomLeading){
                Image("ghost").resizable().aspectRatio(contentMode: .fill)
                LinearGradient(gradient: Gradient(colors: [.clear, .black]),startPoint: .center, endPoint: .bottom).clipped()
                Text(self.cards[row * 3 + column]) // this cause the error
                    .fontWeight(.semibold)

              }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多