如何参照每处一个 lo子里设立的纽顿
我有以下法典,其中我对使用“ForEach loop”创建的一组纽芬兰州适用了一种习俗。 我试图做到两点: 当一个县受到压力时,1台。 如果是正确的纽扣吨,(即与用户匹配)其边界闪光在产生新的用户需求之前是绿色的(我已设法做到大部分), 2. 如果是错的纽顿,那么与用户即时闪电相匹配的纽顿就向用户表示应该受到压力。
I’ve tried two different ways of creating this effect. Firstly using a function that triggers when the button is pressed, passing in the buttons border colour, but this didn’t work as it didn’t allow me to specify which button should flash red in the case of a wrong press. Now I’ve been trying to do it via custom buttonStyle, but this is similar in practice except it does a lot more of what I want.
TLDR ;从本质上讲,我有麻烦地把一个由每个娱乐场所创建的纽州的一个单一案例提到。 我的想象力,我需要把第二个条件列入我的检查条件,即“Ifutton与用户匹配,然后又闪光了那顿红色”。 但是,不能确定如何做到这一点。
这里,我迄今为止已经做了以下工作:
import SwiftUI
struct ContentView: View {
var fullArray = ["1","2","3","4","5","6"]
var topArray = ["1","2","3"]
var botArray = ["4","5","6"]
@State private var userPrompt = ["1","2","3","4","5","6"]
@State private var newLetter = ""
@State private var borderColor = Color.black
@State private var letterTapped = ""
func chosenLetter() -> String {
return userPrompt.randomElement() ?? "Not working"
}
var body: some View {
VStack{
Text(newLetter)
.padding()
.font(.title)
.background(Color.blue)
.foregroundColor(.white)
HStack {
ForEach(topArray, id: .self) { topLetter in
Button(action: {
print("Top number keys")
}){
Text(topLetter)
}
.buttonStyle(CustomButtonStyle(keyLabel: topLetter, newLetter: $newLetter, borderColor: $borderColor))
}
}
HStack{
ForEach(botArray, id: .self){ botLetter in
Button(action:{
print("Bottom number keys")
}){
Text(botLetter)
}
.buttonStyle(CustomButtonStyle(keyLabel: botLetter, newLetter: $newLetter, borderColor: $borderColor))
}
}
.padding()
}
.onAppear {
newLetter = chosenLetter()
}
}
struct CustomButtonStyle: ButtonStyle {
let keyLabel: String
@State var isPressed = false
@Binding var newLetter : String
@Binding public var borderColor: Color
// @Binding var correctLetter : Bool
func chooseBorder() -> Color {
if keyLabel == newLetter {
if isPressed{
return Color.green
}
}else{
return Color.black
}
return Color.black
}
func makeBody(configuration: Configuration) -> some View {
configuration.label
.padding()
.border(chooseBorder())
.onTapGesture {
isPressed = true
// Change border color if label matches userPrompt
if keyLabel == newLetter {
borderColor = .green
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4)
{
borderColor = Color.black
}
}else{
borderColor = .red
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4)
{
borderColor = Color.black
}
}
}
}
}
}
I have tried completing this as a function that runs in the buttons action instead of through a custom button style. One idea I’ve had is that I could generate a dictionary that has each string and an associated value. This might then allow me to reference that button based on its value. But I think I might be over complicating it