SwiftUI-我可以与提取的子视图共享功能吗? [英] SwiftUI - Can I share functions with an extracted subview?

查看:54
本文介绍了SwiftUI-我可以与提取的子视图共享功能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在提取子视图以使代码易于管理,但我遇到的一件事是无法在父视图中调用函数.有人可以给我解释一下最佳做法吗?

I'm extracting subviews to keep my code manageable but one thing I've come up against is not being able to call functions in the parent view. Can someone explain to me the best practice for this please?

这是一个伪示例:

struct MyView: View {
    
    func performAction(){
        //do something here
    }
    
    var body: some View {
        
        ZStack {        
            MySubView()
        }
    }
}

struct MySubView(){
    HStack {
        Button(action: {
            // I want to call performAction() here
        }) {
            Text("Perform action")
        }
    }
}

我考虑过的一个选项是使用绑定,然后在绑定变量的setter中执行操作,但这似乎很麻烦.

One option I've considered is using a binding and then performing the action in the setter of the bound variable, but that seems ungainly.

推荐答案

您可以尝试使用扩展名:

struct MyView: View {
    func performAction() {
        // do something here
    }

    var body: some View {
        ZStack {
            subView
        }
    }
}

extension MyView {
    var subView: some View {
        HStack {
            Button(action: {
                self.performAction()
            }) {
                Text("Perform action")
            }
        }
    }
}

这篇关于SwiftUI-我可以与提取的子视图共享功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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