如何将回调传递给视图初始化函数?

3

这个例子可以运行,但如果我需要添加一个初始化来做一些准备工作,我不知道如何传递回调函数。在实际代码中,我需要传递多个参数并进行一些其他初始化。

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

如何将回调函数作为参数传递?
1个回答

2

它可以像这样

struct Choices: View
{
    let choices = ["One", "Two", "Three"]
    @State var choice:String = "One"
    let callback: (String) -> ()
    
    init(callback: @escaping (String) -> ()) {    // << here !!
        self.callback = callback
    }
// ...
}

甚至可以使用默认值

init(callback: @escaping (String) -> () = { _ in }) {    // << here !!
    self.callback = callback
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接