Home > Blockchain >  How to use a ForEach parameter outside of it in SwiftUI?
How to use a ForEach parameter outside of it in SwiftUI?

Time:07-24

Let's take a simple code:

struct ContentView: View {
    let vocals = ["A", "E", "I", "O", "U"]

    var body: some View {
        HStack {
            ForEach(vocals, id: \.self) { letter in
                Button {
                } label: {
                    Text(letter)
                }
            }
        }
    }
    
    func example() {
       // I would like to use letter here
    }
}

How can I use the letter parameter of the ForEach outside of it?

CodePudding user response:

In case you want to use a single letter to modify the data inside the vocals array, you can use ForEach with index number instead.

struct ContentView: View {
@State var vocals = ["A", "E", "I", "O", "U"]
@State var catchLetter = "" //for store the clicked letter
var body: some View {
    VStack {
        HStack {
            ForEach(0..<vocals.count, id: \.self) { index in
                Button {
                    catchLetter = vocals[index]
                    example(modifyIndex: index)
                } label: {
                    Text(vocals[index])
                }
            }
        }
        Text("Caught letter: \(catchLetter)") //clicked letter
    }
}

func example(modifyIndex: Int) {
    vocals[modifyIndex] = "X" //change the clicked letter to "X"
}
}

CodePudding user response:

Change your function so when you call it from the button it takes an argument

func example(_ letter: String)

Then in the Button you call it

example(letter)

CodePudding user response:

Additional sample solution code(replicated similar problem):

struct TestViewPage: View {
@State var animal: [String] = ["DOG", "CAT", "ELEPHANT", "ANT", "ZEBRA"]
@State var indexCatch = 0
var body: some View {
    TabView(selection: $indexCatch) {
        ForEach(animal.indices, id: \.self) { index in
            Text("swipe to move page\n\(animal[index])")
                .multilineTextAlignment(.center)
                .padding()
                .background(.blue)
                .cornerRadius(10)
        }
    }
    .tabViewStyle(PageTabViewStyle())
    .toolbar {
        ToolbarItem(placement: .navigationBarLeading) {
            Text("Current Page: \(animal[indexCatch])")
        }
        ToolbarItem(placement: .navigationBarTrailing) {
            Button("reset") {
                withAnimation {
                    indexCatch = 0 //go back to first page
                }
            }
        }
    }
}
}
  • Related