使用@ViewBuilder 创建支持多个子节点的视图 [英] Using @ViewBuilder to create Views which support multiple children

查看:31
本文介绍了使用@ViewBuilder 创建支持多个子节点的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SwiftUI 中的一些视图,例如 VStack 和 HStack 支持将多个视图作为子视图,如下所示:

Some Views in SwiftUI, like VStack and HStack support having multiple views as children, like this:

VStack {
  Text("hello")
  Text("world")
}

据我所知,他们使用 ViewBuilder 来使这成为可能,正如所解释的 此处.

From what I gather, they use ViewBuilder to make this possible as explained here.

我们如何使用@ViewBuilder 创建我们自己的支持多个子节点的视图?例如,假设我想创建一个接受任意子元素的 Layout 视图 - 像这样:

How can we use @ViewBuilder for creating our own Views which support multiple children? For example, let's say that I want to create a Layout View which accepts arbitrary children -- something like this:

struct Layout : View {
  let content: Some View 

  var body : some View {
    VStack {
      Text("This is a layout")
      content()
    }
  } 
}

知道如何在 SwiftUI 中实现这种模式吗?

Any idea how to implement this pattern in SwiftUI?

推荐答案

这是一个什么都不做的示例视图,只是为了演示如何使用 @ViewBuilder.

Here's an example view that does nothing, just to demonstrate how to use @ViewBuilder.

struct Passthrough<Content>: View where Content: View {

    let content: () -> Content

    init(@ViewBuilder content: @escaping () -> Content) {
        self.content = content
    }

    var body: some View {
        content()
    }

}

用法:

Passthrough {
    Text("one")
    Text("two")
    Text("three")
}

这篇关于使用@ViewBuilder 创建支持多个子节点的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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