SwiftUI创建将被继承的基视图的最佳方式



我试图找到最好的方法来制作一个视图,它将像一个基本视图一样提供一些默认行为。下面是我目前做得最好的一个例子:

struct BaseView <Content: View>: View{
@Binding var showSideMenu: Bool
let view:  () -> Content
var body: some View {
VStack{
view()
}
.frame(maxWidth:.infinity, maxHeight: .infinity)
.offset(x: showSideMenu ? Screen.width / 1.5 : 0)
.disabled(showSideMenu ? true : false)
.background(Color.red)
.edgesIgnoringSafeArea(.all)
}
}
struct MainView: View {
@Binding var showSideMenu: Bool
var body: some View {
BaseView(showSideMenu: $showSideMenu) {
VStack{
Text("HOME")
Button(action: {
withAnimation {
self.showSideMenu.toggle()
}
}) {
Text("Show Menu")
}
}
}
}
}

这里不好的是BaseView必须首先实现VStack才能像其他view的父视图一样。我想避免这种情况,或者找到更好的解决方案。

如何使用自定义视图修饰符。它获取传入的内容,你不需要额外的堆栈:

struct ContentView: View {

@State var showSideMenu: Bool = false

var body: some View {
VStack{
Text("HOME")
Button(action: {
withAnimation {
self.showSideMenu.toggle()
}
}) {
Text("Show Menu")
}
}
.baseViewModifier(showSideMenu: $showSideMenu)
}
}

extension View {
func baseViewModifier(showSideMenu: Binding<Bool>) -> some View {
self.modifier(BaseViewModifier(showSideMenu: showSideMenu))
}
}
struct BaseViewModifier: ViewModifier {

@Binding var showSideMenu: Bool

func body(content: Content) -> some View {

content
.frame(maxWidth:.infinity, maxHeight: .infinity)
.offset(x: showSideMenu ? UIScreen.main.bounds.width / 1.5 : 0)
.disabled(showSideMenu ? true : false)
.background(Color.red)
.edgesIgnoringSafeArea(.all)
}
}