SwiftUI制作View可嵌套组件
- 了解嵌套组件制造原理
- 制作一套嵌套组件
- 掌握配置嵌套组件的preview的方法
- 如何初始化嵌套参数
- 基础构造
struct ENavigationView<Content: View>: View {
let viewBuilder: () -> Content
var body: some View {
NavigationView {
VStack {
viewBuilder()
.navigationBarTitle("My App")
}
}
}
}
struct ENavigationView_Previews: PreviewProvider {
static var previews: some View {
ENavigationView {
Text("Preview")
}
}
}
struct ContentView: View {
var body: some View {
ENavigationView {
Text("My Text")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
- 初始化参数
struct ENavigationView<Content: View>: View {
let viewBuilder: () -> Content
@Binding var oneFlag:Int
init(oneFlag:Int,, @ViewBuilder content: @escaping () -> Content)
{
self.oneFlag = oneFlag
self.viewBuilder = content
}
var body: some View {
NavigationView {
VStack {
viewBuilder()
.navigationBarTitle("My App")
}
}
}
}
struct ENavigationView_Previews: PreviewProvider {
static var previews: some View {
ENavigationView {
Text("Preview")
}
}
}
struct ContentView: View {
@State var oneFlag = 1
var body: some View {
ENavigationView(oneFlag:self.oneFlag) {
Text("My Text")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
原文地址:https://www.cnblogs.com/liuxiaokun/p/12677007.html
时间: 2024-10-11 11:39:42