繁体   English   中英

如何在 SwiftUI 中使用 ForEach 参数?

[英]How to use a ForEach parameter outside of it in SwiftUI?

我们来看一个简单的代码:

 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 } }

如何在 ForEach 之外使用 letter 参数?

如果您想使用单个字母来修改vocals数组中的数据,您可以使用带index号的ForEach

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"
}
}

更改您的函数,以便当您从按钮调用它时,它需要一个参数

func example(_ letter: String)

然后在 Button 中调用它

example(letter)

附加示例解决方案代码(复制类似问题):

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
                }
            }
        }
    }
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM