SwiftUI - 如何将顶部安全区域的背景颜色更改为灰色?

Tan*_*eek 5 swiftui

我想将顶部安全区域的背景颜色从绿色更改为灰色。我到处寻找但找不到任何解决方案。预览屏幕如下所示。

在此输入图像描述

我的代码:

struct ContentView: View {
    @State var name = ""
    init() {
            //Use this if NavigationBarTitle is with Large Font
           UINavigationBar.appearance().largeTitleTextAttributes = [.foregroundColor: UIColor.red]
           UINavigationBar.appearance().backgroundColor = .gray
        }
    var body: some View {
        NavigationView {
            
            ZStack{
                VStack{
                    TextField("Name", text: $name)
                        .frame(height:200)
                        .padding()
                        .background(backgrounImage())
                        .overlay(RoundedRectangle(cornerRadius: 20).stroke(Color.gray,lineWidth: 4))
                        .padding()
                    Spacer()
                }.navigationTitle("Tanvir")
                .background(Color.green.edgesIgnoringSafeArea(.all))
            }
            
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Moj*_*ini 8

您可以在以下视图之上添加另一个视图ZStack

    var body: some View {
        NavigationView {
            ZStack(alignment: .top) { // <- Don't forget this
                ,,,
 
                GeometryReader { reader in
                    Color.yellow
                        .frame(height: reader.safeAreaInsets.top, alignment: .top)
                        .ignoresSafeArea()
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

不要忘记堆栈对齐!

在此输入图像描述

整个应用程序的一致栏

如果您需要它出现在所有视图上,请尝试将代码放在更一致的位置,例如您提供的位置contentView

@main
struct SwiftUIAppPlaygroundApp: App {
    var body: some Scene {
        WindowGroup {
            ZStack {
                ContentView()

                GeometryReader { reader in
                    Color.yellow
                        .frame(height: reader.safeAreaInsets.top, alignment: .top)
                        .ignoresSafeArea()
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)