SwiftUI 的新手,并尝试在 LazyVGrid 内的单独 CardViews 上显示这些表情符号。当我使用 ForEach 循环为每个 CardView 设置一个表情符号时,我不能使用重复的表情符号 - 即使我使用过id: \.self
(实际上,并不完全确定这对我想要实现的目标很重要,但认为值得一提)。
基本上,我可以显示 5 张卡片,但是当我尝试显示 6 张(即重复项目开始时)时,预览会崩溃。我可以用 HStack 做到这一点,但由于某种原因,不能用 LazyVStack。我查看了 LazyVStack 文档,但找不到答案。
此外,尝试在 ForEach 中使用 .indicies 但似乎也没有修复它。
import SwiftUI
struct ContentView: View {
var emojis: [String] = ["", "", "", "",
"", "", "", "",
"", "", "", "",
"", "", "", "",
"", "", "", "",
"", "", "", ""]
@State var emojiCount = 5 //6
var gridLayout = [GridItem(), GridItem(), GridItem()]
var body: some View {
VStack {
LazyVGrid(columns: gridLayout) {
// HStack {
ForEach((emojis[0..<emojiCount]), id: \.self) { emoji in
CardView(content: emoji)
}
}
.foregroundColor(.red)
Spacer()
HStack {
remove
Spacer()
add
}
}
.padding(.horizontal)
}
var add: some View {
Button(action: {
emojiCount += 1
}, label: {
Text("⨁")
})
}
var remove: some View {
Button(action: {
if emojiCount > 0 {
emojiCount -= 1
}
}, label: {
Text("⊖")
})
}
}
struct CardView: View {
var content: String
@State var isFaceUp: Bool = true
var body: some View {
ZStack {
let shape = RoundedRectangle(cornerRadius: 20.0)
if isFaceUp {
shape.fill().foregroundColor(.white)
shape.stroke(lineWidth: 3.0)
Text(content)
} else {
shape.fill()
}
}
.onTapGesture {
isFaceUp = !isFaceUp
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.preferredColorScheme(.dark)
ContentView()
.preferredColorScheme(.light)
}
}
struct ContentView_Previews_2: PreviewProvider {
static var previews: some View {
/*@START_MENU_TOKEN@*/Text("Hello, World!")/*@END_MENU_TOKEN@*/
}
}