【问题标题】:SwiftUI - How do I change the background color of a View?SwiftUI - 如何更改视图的背景颜色?
【发布时间】:2019-10-19 13:54:51
【问题描述】:

我开始尝试SwiftUI,我很惊讶更改View 的背景颜色似乎并不简单。你如何使用SwiftUI 做到这一点?

【问题讨论】:

    标签: view background background-color modifier swiftui


    【解决方案1】:

    屏幕背景颜色

    (截至 Xcode 版本 13)

    我不确定原始海报是指整个屏幕的背景颜色还是个别视图的背景颜色。所以我将添加这个答案,即设置整个屏幕的背景颜色。

    使用 ZStack

    var body: some View {
        ZStack {
                Color.purple
                    .ignoresSafeArea()
                
                // Your other content here
                // Other layers will respect the safe area edges
        }
    }
    

    我添加了.ignoresSafeArea(),否则它会停在安全区域边缘。

    使用叠加修饰符

    var body: some View {
        Color.purple
            .ignoresSafeArea(.vertical) // Ignore just for the color
            .overlay(
                VStack(spacing: 20) {
                    Text("Overlay").font(.largeTitle)
                    Text("Example").font(.title).foregroundColor(.white)
            })
    }
    

    注意:将.ignoresSafeArea 保持在颜色上很重要,这样您的主要内容也不会忽略安全区域的边缘。

    iOS 15

    iOS 15/Xcode 13 对样式处理安全区域边缘的方式进行了一些更改。

    根据我的观察,规则是:如果样式接触到安全区边缘,就会渗入安全区。

    这为您提供了更多设置背景颜色/样式的选项。

    什么是样式?

    样式可以是:

    • 颜色
    • 材质(模糊效果)
    • 分层视图(.secondary、.tertiary、.quaternary)
    • 渐变

    使用背景

    因为VStack的背景接触了安全区的边缘,紫色会渗入安全区。

    var body: some View {
        VStack {
            Text("Hello, World!")
            Divider()
            Spacer()
        }
        .background(Color.purple)
    }
    

    标签视图

    在 iOS 15 中,TabView 不再是半透明的。这意味着背景颜色会渗入其中。

    如果您想为您的 TabView 提供自定义样式,您可以添加另一个样式,该样式触及底部安全区域边缘,以便渗入您的 TabView。例如:

    var body: some View {
        TabView {
            VStack {
                Text("Hello, World!")
                Divider()
                Spacer()
                // Bleeds into TabView
                Rectangle()
                    .frame(height: 0)
                    .background(.thinMaterial)
            }
            .background(Color.purple)
            .tabItem {
                Text("Tab 1")
                Image(systemName: "wifi")
            }
        }
    }
    

    导航视图

    发生在 TabView 上的事情也会发生在 NavigationView 上。

    要自定义 NavigationView 样式,请添加一个会触及顶部安全区域边缘的样式,它将渗入 NavigationView:

    var body: some View {
        NavigationView {
            VStack {
                // Bleeds into NavigationView
                Rectangle()
                    .frame(height: 0)
                    .background(.ultraThinMaterial)
                Text("Hello, World!")
                Divider()
                Spacer()
            }
            .background(Color.purple)
            .navigationTitle(Text("Style"))
        }
    }
    

    我完全愿意通过其他方式来实现这一点。如果您知道其他方式,请发表评论或编辑此答案。

    【讨论】:

    • 你知道如何更改 NavigationView 的背景颜色吗?
    • 这会起作用,但是如果你有一个 NavigationView 和一个列表或滚动视图,导航栏标题将不会折叠
    • 我只是尝试了两个都没有运气。我一直在想办法让屏幕背景颜色与导航视图和滚动视图一起使用
    • 嘿@Ryan,我更新了我的解决方案以将.edgesIgnoringSafeArea(.all) 移动到仅颜色而不是任何其他内容。这应该更适合您。
    • 关于 NavigationView,在 NavigationView 内部使用上面的 ZStack 方法,如下所示:stackoverflow.com/a/58230473/457478
    【解决方案2】:

    填满整个屏幕:

    var body: some View {
        Color.green.edgesIgnoringSafeArea(.all)
    }
    
    Code Result

    【讨论】:

      【解决方案3】:
      struct Soview: View {
          var body: some View {
              VStack{
                  Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
                      .frame(maxWidth:.infinity,maxHeight: .infinity)
              }.background(Color.yellow).ignoresSafeArea(.all)
          }
      }
      

      【讨论】:

        【解决方案4】:

        导航视图示例:

        var body: some View {
            var body: some View {
                NavigationView {
                    ZStack {
                        // Background
                        Color.blue.edgesIgnoringSafeArea(.all)
        
                        content
                    }
                    //.navigationTitle(Constants.navigationTitle)
                    //.navigationBarItems(leading: cancelButton, trailing: doneButton)
                    //.navigationViewStyle(StackNavigationViewStyle())
                }
            }
        }
        
        var content: some View {
            // your content here; List, VStack etc - whatever you want
            VStack {
               Text("Hello World")
            }
        }
        

        【讨论】:

          【解决方案5】:

          Xcode 11.5

          只需使用 ZStack 将背景颜色或图像添加到 SwiftUI 中的主视图

          struct ContentView: View {
              var body: some View {
                  ZStack {
                      Color.black
                  }
                  .edgesIgnoringSafeArea(.vertical)
              }
          }
          

          【讨论】:

            【解决方案6】:

            Swift UI中的场景委托代码

            内容视图背景色

            window.rootViewController?.view.backgroundColor = .lightGray

            【讨论】:

              【解决方案7】:

              我喜欢声明一个修改器来改变视图的背景颜色。

              extension View {
                func background(with color: Color) -> some View {
                  background(GeometryReader { geometry in
                    Rectangle().path(in: geometry.frame(in: .local)).foregroundColor(color)
                  })
                }
              }
              

              然后我通过将颜色传递给视图来使用修饰符。

              struct Content: View {
              
                var body: some View {
                  Text("Foreground Label").foregroundColor(.green).background(with: .black)
                }
              
              }
              

              【讨论】:

                【解决方案8】:

                使用以下代码自定义导航栏颜色

                struct ContentView: View {
                
                @State var msg = "Hello SwiftUI?"
                init() {
                    UINavigationBar.appearance().backgroundColor = .systemPink
                
                     UINavigationBar.appearance().largeTitleTextAttributes = [
                        .foregroundColor: UIColor.white,
                               .font : UIFont(name:"Helvetica Neue", size: 40)!]
                
                    // 3.
                    UINavigationBar.appearance().titleTextAttributes = [
                        .font : UIFont(name: "HelveticaNeue-Thin", size: 20)!]
                
                }
                var body: some View {
                    NavigationView {
                    Text(msg)
                        .navigationBarTitle(Text("NAVIGATION BAR"))       
                    }
                    }
                }
                

                【讨论】:

                  【解决方案9】:

                  您可以简单地更改视图的背景颜色:

                  var body : some View{
                  
                  
                      VStack{
                  
                          Color.blue.edgesIgnoringSafeArea(.all)
                  
                      }
                  
                  
                  }
                  

                  你也可以使用 ZStack :

                  var body : some View{
                  
                  
                      ZStack{
                  
                          Color.blue.edgesIgnoringSafeArea(.all)
                  
                      }
                  
                  
                  }
                  

                  【讨论】:

                    【解决方案10】:

                    你可以这样做:

                    .background(Color.black)
                    

                    围绕您的视野。

                    例如。从默认模板(我将它包含在一个组周围):

                        var body: some View {
                            VStack {
                              Text("Hello SwiftUI!")
                            }
                           .background(Color.black)
                        }
                    

                    要为其添加一些不透明度,您也可以添加.opacity 方法:

                    .background(Color.black.opacity(0.5))
                    

                    您还可以通过 CMD 使用视图的检查元素 + 单击视图并单击 Show SwiftUI Inspector > Background > 您的颜色

                    【讨论】:

                    • 我不能将它用于导航视图你知道如何处理导航视图吗?
                    • 你用的是什么版本?
                    • atalayasa, UINavigationBar.appearance().backgroundColor = .black
                    • 当我使用 Rectangle() 执行此操作时,我最终会得到一个黑色填充区域。
                    • 此方法比其他告诉您将Color() 直接插入视图的答案更可取,因为.background() 不会改变视图的隐式大小(如果您将其应用于子视图)。
                    【解决方案11】:

                    对于List

                    所有 SwiftUI 的 Lists 都由 iOS 中的 UITableView支持。所以你需要改变tableView的背景颜色。但由于ColorUIColor 的值略有不同,可以去掉UIColor

                    struct ContentView : View {
                        init(){
                            UITableView.appearance().backgroundColor = .clear
                        }
                        
                        var body: some View {
                            List {
                                Section(header: Text("First Section")) {
                                    Text("First Cell")
                                }
                                Section(header: Text("Second Section")) {
                                    Text("First Cell")
                                }
                            }
                            .background(Color.yellow)
                        }
                    }
                    

                    现在您可以使用您想要的任何背景(包括所有Colors)


                    也先看看这个结果:

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

                    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(还)的背景颜色,因此我们无法通过视图层次结构看到像 navigationView 这样的一些视图。您应该等待 API 或尝试伪造这些视图(不推荐)。

                    【讨论】:

                    • 一个类似的问题,而不是在列表行上设置颜色,我怎样才能使它透明,似乎我所有的尝试都未能揭示底层颜色并且行保持白色,特别是ListCoreCellHost保持白色。 pasteboard.co/JeWCgMV.png
                    • 好吧,我想 15 分钟后在这里发帖,也必须设置 UITableViewCell.appearance().backgroundColor = .clear。 :)
                    【解决方案12】:

                    几种可能性:(SwiftUI / Xcode 11)

                    1 .background(Color.black) //for system colors

                    2.background(Color("green")) //for colors you created in Assets.xcassets

                    1. 否则,您可以在元素上执行 Command+Click 并从那里更改它。

                    希望对你有帮助:)

                    【讨论】:

                      【解决方案13】:

                      这个解决方案行得通吗?:

                      在 SceneDelegate 中添加以下行:window.rootViewController?.view.backgroundColor = .black

                      func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
                              if let windowScene = scene as? UIWindowScene {
                      
                                      window.rootViewController?.view.backgroundColor = .black
                      }
                      

                      【讨论】:

                        【解决方案14】:

                        喜欢这个

                        struct ContentView : View {
                            @State var fullName: String = "yushuyi"
                            var body: some View {        
                                VStack
                                    {
                                        TextField($fullName).background(SwiftUI.Color.red)
                                        Spacer()
                                }.background(SwiftUI.Color.yellow.edgesIgnoringSafeArea(.all))
                            }
                        }
                        

                        【讨论】:

                        • 请注意,您需要将.edgesIgnoringSafeArea() 添加到背景颜色。来自 UIKit 这很奇怪,但它有效!
                        • 注意:这是因为 Spacer() 将 VStack 推到屏幕的高度。
                        猜你喜欢
                        • 2022-01-25
                        • 2020-03-02
                        • 1970-01-01
                        • 2020-05-15
                        • 2021-02-11
                        • 1970-01-01
                        • 2021-07-25
                        • 2022-01-15
                        相关资源
                        最近更新 更多