我正在学习斯坦福大学的CS193p,一切都进行得很顺利,直到把LazyVGrid换成HStack为止。
我和一位教授核对了我的代码,它们是一样的。但是,我的代码中令人困惑的部分是,当我的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
}
}
}我一整晚都想弄清楚,但我还是不知道我的代码出了什么问题。非常感谢!
发布于 2021-05-29 18:19:47
在模拟器中运行代码,您将看到错误。
致命错误:每个布局项只能发生一次。
这就产生了表情符号。你有很多,但只有4种不同的类型。在由\.self引用项的循环中,您负责确保项是唯一的。
https://stackoverflow.com/questions/67754403
复制相似问题