SwiftUI 回调作为视图的参数 [英] SwiftUI callback as parameter to a view

查看:36
本文介绍了SwiftUI 回调作为视图的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的 SwiftUI 视图拆分为尽可能小的可重用组件.所以我有位于顶部的 MainView,然后有两个视图(MyContentView 和 MenuView),它们都位于 MainView 中.两个内部视图都有一些我想在 MainView 中更新某些内容的功能.所以我想我可以将一些函数作为参数从 MainView 传递给内部视图,所以当在内部视图中按下按钮时,它会触发 MainView 中的代码.我设法最接近它的是导致每次更新内部视图时都会触发函数参数.实现这一目标的最佳方法是什么?这是我的代码示例:

I'm trying to split my SwiftUI views to as small-reusable components as possible. So I have MainView which is at the top, and then two views (MyContentView and MenuView) that both live inside MainView. Both the inner views have some functionality that I want to be updating something in the MainView. So I thought I could pass some function as a parameter to the inner views from the MainView, so when the button is pressed in the inner views it would trigger code in the MainView. The closest I managed to get to it is causing the function parameter to be triggered on every update of the inner View. What is the best way to achieve that? Here is an example of my code:

主视图:

struct MainView: View {
    var body: some View {
         VStack {
             MyContentView(self.$doSomething)
             MenuView(self.$doSomething)
         }
    }

    func doSomething() {
        print("do something")
    }
}

struct MyContentView : View {
    var doSomething : ()
    var body: some View {
        Button(action: { self.doSomething }) { Text("do something") }
    }
}

struct MenuView : View {
    var doSomething : ()
    var body: some View {
        Button(action: { self.doSomething }) { Text("Menu do something") }
    }
}

能够从内部视图接收回调的最佳实践是什么?

What is the best practice to be able to receive callbacks from inner views?

推荐答案

以下变体作品.使用 Xcode 11.4 测试.

Below variant works. Tested with Xcode 11.4.

struct MainView: View {
    var body: some View {
         VStack {
             MyContentView(doSomething: self.doSomething)
             MenuView(doSomething: self.doSomething)
         }
    }

    func doSomething() {
        print("do something")
    }
}

struct MyContentView : View {
    var doSomething : () -> ()
    var body: some View {
        Button(action: { self.doSomething() }) { Text("do something") }
    }
}

struct MenuView : View {
    var doSomething : () -> ()
    var body: some View {
        Button(action: { self.doSomething() }) { Text("Menu do something") }
    }
}

这篇关于SwiftUI 回调作为视图的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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