我正在学习斯坦福 CS193p,一切都很顺利,直到用 HStack 切换 LazyVGrid。
我和一位教授检查了我的代码,它们是一样的。但是我的代码中令人困惑的部分是,当我的 emojiCount = 4,预览效果很好时,我可以使用 LazyVGrid,但是当我将 emojiCount 值更改为 4 以上时,例如 5 或 24,它会立即崩溃。
崩溃信息是这样的:
这是我的代码:
import SwiftUI
struct ContentView: View {
var emojis = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]
@State var emojiCount = 4
var body: some View {
VStack {
LazyVGrid(columns:[GridItem(),GridItem(),GridItem()]) {
ForEach(emojis[0..<emojiCount], id: \.self) { emoji in
CardView(content: emoji)
}
}
.foregroundColor(.red)
Spacer()
HStack {
remove
Spacer()
add
}
.font(.largeTitle)
.padding(.horizontal)
}
.padding(.horizontal)
}
var remove: some View {
Button {
if emojiCount > 2 {
emojiCount -= 1
}
} label: {
Image(systemName:"minus.circle")
}
}
var add: some View {
Button {
if emojiCount < emojis.count {
emojiCount += 1
}
} label: {
Image(systemName:"plus.circle")
}
}
}
struct CardView: View {
var content: String
@State var isFaceUp: Bool = true
var body: some View {
ZStack {
let shape = RoundedRectangle(cornerRadius: 20)
if isFaceUp {
shape.fill().foregroundColor(.white)
shape.stroke(lineWidth: 3)
Text(content).font(.largeTitle)
} else {
shape.fill()
}
}
.onTapGesture {
isFaceUp = !isFaceUp
}
}
}
我试图弄清楚整个晚上,但我仍然不知道我的代码有什么问题。非常感谢!