In my ContentView
I have two buttons, red and green, when I click on each of them i change and then append them to an empty array that gets filled and display its items in my SecondView
.
I would like to show a green name when i tap on the green button and a red one when i tap on the red button, how can i achieve this?
Here is the code:
ContentView
struct ContentView: View {
@State private var countdown = Timer.publish(every: 1, tolerance: 0.5, on: .main, in: .common).autoconnect().eraseToAnyPublisher()
@State private var timeRemaining = 10
@State private var isActive = false
@State private var names = ["Steve", "Bill", "Jeff", "Elon", "Michael", "John", "Steven", "Paul"]
@State private var appearedNames = [String]()
@State private var currentPerson = ""
var body: some View {
NavigationView {
ZStack {
NavigationLink(destination: SecondView(appearedNames: $appearedNames, countdown: countdown), isActive: $isActive) {
EmptyView()
}
VStack {
Text("\(timeRemaining)")
.font(.largeTitle)
.padding()
.onReceive(countdown) { _ in
if timeRemaining > 0 {
timeRemaining -= 1
}
if timeRemaining == 0 {
isActive = true
}
}
HStack {
Button {
appearedNames.append(currentPerson)
changePerson()
} label: {
Text(currentPerson)
.foregroundColor(.red)
.font(.largeTitle)
}
Button {
appearedNames.append(currentPerson)
changePerson()
} label: {
Text(currentPerson)
.foregroundColor(.green)
.font(.largeTitle)
}
}
}
.onAppear {
changePerson()
}
}
}
}
func changePerson() {
if names.count > 0 {
let index = Int.random(in: 0..<names.count)
currentPerson = names[index]
names.remove(at: index)
}
}
}
SecondView
import SwiftUI
import Combine
struct SecondView: View {
@Binding var appearedNames: [String]
var countdown: AnyPublisher<Date,Never>
@State private var counter = 0
var body: some View {
VStack {
ScrollViewReader { proxy in
ScrollView(showsIndicators: false) {
ForEach(0...counter, id: \.self) { index in
Text(appearedNames[index])
.font(.system(size: 70))
.id(index)
.onAppear {
proxy.scrollTo(index)
}
}
}
}
}
.navigationBarBackButtonHidden(true)
.onReceive(countdown) { _ in
if counter < appearedNames.count - 1 {
counter += 1
}
}
}
}