从子视图到父视图在swiftui中调用函数?

时间:2020-05-16 19:31:50

标签: ios swift swiftui

我在子视图中有一个函数,其中包含另外两个函数。

struct PKCanvas: UIViewRepresentable {
class Coordinator: NSObject, PKCanvasViewDelegate {
    var pkCanvas: PKCanvas

    init(_ pkCanvas: PKCanvas) {
        self.pkCanvas = pkCanvas

    }

}
func detectImage() { //this is the function 
       let image = preprocessImage()
       predictImage(image: image)

             }

我想在父视图中调用它。找不到方法。请帮助。

struct ContentView: View {
@State var color = UIColor.white
@State var clear = false
@State var classificationLabel: String = ""
let canvas = PKCanvasView()
var body: some View {
    VStack{
        PKCanvas(color: $color, clear:$clear)
        VStack(){
            Button("Pencil"){ self.color = UIColor.black }
            Button("Classify"){
                self.detectImage() //want to call here
            }
            Button("Clear Canvas"){ self.clear.toggle() }
        }
     }
  }
} 

1 个答案:

答案 0 :(得分:0)

首先请确保您确认遵守UIViewRepresentable协议。

我为您制作了一个演示,只是为了演示该呼叫是否正常工作

struct PKCanvas: UIViewRepresentable {

    func makeUIView(context: UIViewRepresentableContext<PKCanvas>) -> UIView {
        //just an example view
        let view = UIView(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
        view.backgroundColor = color

        return view
    }

    func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PKCanvas>) {
    }

    //this method is getting called by parent
    func test() -> Void
    {
        NSLog("Test")
    }

    typealias UIViewType = UIView

}

然后创建该视图并在视图中使用它。您在实例变量上调用该方法。

struct ContentView: View {
@State var color = UIColor.white
@State var clear = false
@State var classificationLabel: String = ""
//create the Canvas view
let canvas = PKCanvas()
var body: some View {
    VStack{
        self.canvas

        VStack(){
            Button("Pencil"){ self.color = UIColor.black }
            Button("Classify"){
                //call the canvas method
                self.canvas.test()
            }
            Button("Clear Canvas"){ self.clear.toggle() }
        }
     }
  }
}