如何在 SwiftUI 中更改 NavigationView 的背景颜色? [英] How to change background color of the NavigationView in SwiftUI?

查看:72
本文介绍了如何在 SwiftUI 中更改 NavigationView 的背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码更改 NavigationView(不是导航栏)的背景颜色:

I'm trying to change background color of the NavigationView (not navigation bar) using this code:

NavigationView {
    Text("Text")
}
.background(Color.clear)

但它不起作用.另外,我尝试更改 UIView 外观:

But it doesn't work. Also, I tried to change UIView appearance:

UIView.appearance().backgroundColor = UIColor.black

但它也不起作用.

实际结果如下:

想要的结果是:

有人知道怎么做吗?

推荐答案

先看这个结果:

如您所见,您可以像这样设置 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://stackoverflow.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).

这篇关于如何在 SwiftUI 中更改 NavigationView 的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆