[英]How can I add a custom container view in SwiftUI
I'm curious if you can create a custom container view within SwiftUI.我很好奇您是否可以在 SwiftUI 中创建自定义容器视图。 I know that you can create custom content views, such as Text()
, but wasn't sure if you could replicate the functionality of say HStack { }
我知道您可以创建自定义内容视图,例如Text()
,但不确定您是否可以复制HStack { }
的功能
Something akin to:类似于:
HGrid {
Text("Lorem ipsum")
Text("Lorem ipsum")
}
Where the custom container view (aka HGrid
) would then, say, add Spacer()
between each added component.然后,自定义容器视图(又名HGrid
)将在每个添加的组件之间添加Spacer()
。 Essentially, as an example, transpiling it to:本质上,例如,将其转换为:
HStack {
Text("Lorem ipsum")
Spacer()
Text("Lorem ipsum")
}
SwiftUI
implements this with the ViewBuilder
@functionBuilder
SwiftUI
与实现此ViewBuilder
@functionBuilder
struct HGrid <Content: View>: View {
init(@ViewBuilder builder: () -> Content) {
let content = builder()
...
}
}
See also也可以看看
If we try to keep it simple and do the only thing, two options can be proposed:如果我们尽量保持简单并只做一件事,可以提出两种选择:
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()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.