且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 SwiftUI 中更改 NavigationView 的背景颜色?

更新时间:2023-12-04 19:04:22

先看这个结果:

如您所见,您可以像这样设置 View 层次结构中每个元素的颜色:

As you can see, you can set the color of each element in the View hierarchy like this:

struct ContentView: View {

    init(){
        UINavigationBar.appearance().backgroundColor = .green 
        //For other NavigationBar changes, look here:(https://***.com/a/57509555/5623035)
    }

    var body: some View {
        ZStack {
            Color.yellow
            NavigationView {
                ZStack {
                    Color.blue
                    Text("Some text")
                }
            }.background(Color.red)
        }
    }
}

第一个是window:

window.backgroundColor = .magenta

您面临的问题是我们无法删除 SwiftUI 的 HostingViewController 的背景颜色(还),因此您无法通过视图层次结构.您应该等待 API 或尝试伪造导航视图(不推荐).

The issue you faced is we can not remove the background color of SwiftUI's HostingViewController (yet), so you can't see the navigationView (What you called) through the views hierarchy. You should wait for the API or try to fake the navigation view (not recommended).