如何在 SwiftUI 中添加自定义容器视图
How can I add a custom container view in SwiftUI
我很好奇您是否可以在 SwiftUI 中创建自定义容器视图。我知道您可以创建自定义内容视图,例如 Text()
,但不确定您是否可以复制 HStack { }
的功能
类似于:
HGrid {
Text("Lorem ipsum")
Text("Lorem ipsum")
}
然后,自定义容器视图(又名 HGrid
)会在每个添加的组件之间添加 Spacer()
。本质上,例如,将其转换为:
HStack {
Text("Lorem ipsum")
Spacer()
Text("Lorem ipsum")
}
SwiftUI
通过 ViewBuilder
@functionBuilder
实现
struct HGrid <Content: View>: View {
init(@ViewBuilder builder: () -> Content) {
let content = builder()
...
}
}
另见
如果我们尽量保持简单,只做一件事,可以提出两个方案:
import SwiftUI
// Via custom containers
struct HGrid<Content: View>: View {
let C1: Content
let C2: Content
var body: some View {
HStack {
C1
Spacer()
C2
}
}
}
// Via View composition
struct HGridComposition: View {
var text1: String
var text2: String
var body: some View {
HStack {
Text(text1)
Spacer()
Text(text2)
}
}
}
struct ContentView: View {
var body: some View {
VStack {
Text("Composed from Views").font(.headline)
HGrid(C1: Text("First"), C2: Text("Second"))
Divider()
Text("Composed from texts (String)").font(.headline)
HGridComposition(text1: "Text One", text2: "Text Two")
}
.padding([.leading, .trailing])
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
我很好奇您是否可以在 SwiftUI 中创建自定义容器视图。我知道您可以创建自定义内容视图,例如 Text()
,但不确定您是否可以复制 HStack { }
类似于:
HGrid {
Text("Lorem ipsum")
Text("Lorem ipsum")
}
然后,自定义容器视图(又名 HGrid
)会在每个添加的组件之间添加 Spacer()
。本质上,例如,将其转换为:
HStack {
Text("Lorem ipsum")
Spacer()
Text("Lorem ipsum")
}
SwiftUI
通过 ViewBuilder
@functionBuilder
struct HGrid <Content: View>: View {
init(@ViewBuilder builder: () -> Content) {
let content = builder()
...
}
}
另见
如果我们尽量保持简单,只做一件事,可以提出两个方案:
import SwiftUI
// Via custom containers
struct HGrid<Content: View>: View {
let C1: Content
let C2: Content
var body: some View {
HStack {
C1
Spacer()
C2
}
}
}
// Via View composition
struct HGridComposition: View {
var text1: String
var text2: String
var body: some View {
HStack {
Text(text1)
Spacer()
Text(text2)
}
}
}
struct ContentView: View {
var body: some View {
VStack {
Text("Composed from Views").font(.headline)
HGrid(C1: Text("First"), C2: Text("Second"))
Divider()
Text("Composed from texts (String)").font(.headline)
HGridComposition(text1: "Text One", text2: "Text Two")
}
.padding([.leading, .trailing])
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}