这个例子是可行的,但如果我需要添加init来做一些准备工作,我就无法找到传递回调的方法.在实际代码中,我需要传递几个参数并进行一些其他初始化.
import SwiftUI
struct Choices: View
{
let choices = ["One", "Two", "Three"]
@State var choice:String = "One"
let callback: (String) -> ()
/*
init()
{
// do stuff here
}
*/
var body: some View
{
VStack(alignment: .leading)
{
ForEach(choices, id:\.self)
{ c in
HStack
{
Image(systemName: (choice == c) ? "checkmark.square" : "square")
Text(c)
}.onTapGesture
{
choice = c
callback(c)
}
}
Divider()
}.padding()
}
}
struct ChoicesContentView: View
{
@State var answers:[String] = ["","",""]
var body: some View
{
VStack(alignment: .leading)
{
ForEach(0..<3)
{ i in
Choices()
{
ans in
print(ans)
}
Text("Selected: \(answers[i])")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ChoicesContentView()
}
}
如何将回调作为参数传递?
谢谢你的帮助.