Here is a possible solution
import SwiftUI
struct ContentView: View {
@State var tapped1 = false
@State var tapped2 = false
@State var tapped3 = false
@State private var randomString = ""
var body: some View {
TestView(tap1: self.$tapped1, tap2: self.$tapped2, tap3: self.$tapped3)
}
}
struct TestView: View {
@Binding var tap1:Bool
@Binding var tap2:Bool
@Binding var tap3:Bool
@State var answer1 = false
@State var answer2 = true
@State var answer3 = false
@State private var timeSpent = 0
@State private var timeSpent2 = 0
@State private var timeSpent3 = 0
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
VStack {
Text("question")
Spacer()
//Resetting the timeSpent which calculates how many seconds flow since user tapped the button
Button(action:{
self.timeSpent = 0
self.tap1 = false
self.timeSpent2 = 0
self.tap2 = false
self.timeSpent3 = 0
self.tap3 = false
})
{
Text("Resetting")
}
VStack {
Button(action: {
self.validate(0)
self.tap1 = true
}) {
HStack{
Text("Answer 1").foregroundColor(Color.black)
}.frame(width:100, height: 30)
.background(timeSpent >= 1 ? (answer1 ? Color.green : Color.red) : Color.blue.opacity(tap1 ? 1 : 0))
}
Button(action: {
self.validate(1)
self.tap2 = true
}) {
HStack{
Text("Answer 2").foregroundColor(Color.black)
}.frame(width:100, height: 30)
.background(timeSpent2 >= 1 ? (answer2 ? Color.green : Color.red) : Color.blue.opacity(tap2 ? 1 : 0))
}
Button(action: {
self.validate(2)
self.tap3 = true
}) {
HStack{
Text("Answer 3").foregroundColor(Color.black)
}.frame(width:100, height: 30)
.background(timeSpent3 >= 1 ? (answer3 ? Color.green : Color.red) : Color.blue.opacity(tap3 ? 1 : 0))
}
}.onReceive(timer) { time in
if self.tap1 {
self.timeSpent += 1
}
if self.tap2 {
self.timeSpent2 += 1
}
if self.tap3 {
self.timeSpent3 += 1
}
}
}
}
private func validate(_ index: Int) {
// check answer
}
}
I used timer to check how many seconds pasted since user tapped the button.
You can set background color like this using nil coalescing:
User didn't tap the button yet
Set the random color and it's opacity to 0
User tapped the button
2-1. Second pasted less than one second -> Blue
2-2.Second pasted more than one second
correct answer -> green,
wrong answer -> red