SwiftUI - 按钮 - 如何将函数请求传递给父级 [英] SwiftUI - Button - How to pass a function request to parent

查看:37
本文介绍了SwiftUI - 按钮 - 如何将函数请求传递给父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让按钮执行触发其父"视图中的功能的操作?我正在尝试重构我的代码,以便组件尽可能小.

How can I have a button perform an action which triggers a function in its 'parent' view? I'm trying to refactor my code so that components are as small as possible.

在这种情况下,按钮执行一些任务,但其中之一是运行一个函数:

In this case, the button performs a few tasks, but one of them is to run a function:

Button(
 action: {
  self.setViewBackToNil()
 }){
  Text("Button")
}

// which triggers a function
func setViewBackToNil(){
 self.userData.image = nil
 self.isProcessing = false
 .... etc
}

现在,如果我将按钮转换为它自己的视图,我将无法传递 self.setViewBackToNil,因为它包含在父级的结构中.

Now, if I turn the button into its own view, I can't pass self.setViewBackToNil because it's contained within the struct of the parent.

有没有办法让组件在其父级中触发一个函数?

Is there a way for a component to trigger a function within its parent?

推荐答案

这是一个关于如何将闭包传递给子视图然后调用父视图的小示例:

This is a small example on how to pass a closure to your child view which then calls a function of the parent:

struct ChildView: View {
    var function: () -> Void
    
    var body: some View {
        Button(action: {
            self.function()
        }, label: {
            Text("Button")
        })
    }
}

struct ParentView: View {
    var body: some View {
        ChildView(function: { self.fuctionCalledInPassedClosure() })
    }
    
    func fuctionCalledInPassedClosure() {
        print("I am the parent")
    }
}

我希望这会有所帮助!

这是一个传递函数的例子:

And here is an example to pass the function:

struct ChildView: View {
    var function: () -> Void
    
    var body: some View {
        Button(action: {
            self.function()
        }, label: {
            Text("Button")
        })
    }
}

struct ParentView: View {
    var body: some View {
        ChildView(function: self.passedFunction)
    }
    
    func passedFunction() {
        print("I am the parent")
    }
}

这篇关于SwiftUI - 按钮 - 如何将函数请求传递给父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆