这个例子可以运行,但如果我需要添加一个初始化来做一些准备工作,我不知道如何传递回调函数。在实际代码中,我需要传递多个参数并进行一些其他初始化。
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()
}
}
如何将回调函数作为参数传递?