您可以引入自定义ViewModifier,如前所述
here
工作示例:
import SwiftUI
struct NavigationBarModifier: ViewModifier {
var backgroundColor: UIColor?
init(backgroundColor: UIColor?) {
self.backgroundColor = backgroundColor
}
func body(content: Content) -> some View {
ZStack{
content
VStack {
GeometryReader { geometry in
Color(self.backgroundColor ?? .clear)
.frame(height: geometry.safeAreaInsets.top)
.edgesIgnoringSafeArea(.top)
Spacer()
}
}
}
}
}
extension View {
func navigationBarColor(_ backgroundColor: UIColor?) -> some View {
self.modifier(NavigationBarModifier(backgroundColor: backgroundColor))
}
}
struct MyContentView: View {
var body: some View {
NavigationView {
ScrollView {
VStack(spacing: 8) {
Text("One")
.roundedContainer()
Text("Two")
.roundedContainer()
}
.padding()
}
.background(Color(.systemGroupedBackground))
.navigationBarTitle("Summary", displayMode: .large)
.navigationBarColor(.systemGroupedBackground)
}
}
}