我开始尝试SwiftUI,我很惊讶,它似乎不是简单的改变一个视图的背景颜色。你如何使用SwiftUI做到这一点?


当前回答

填充整个屏幕:

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

其他回答

(SwiftUI / Xcode 11)

1 .background(Color.black) //系统颜色

2 .background(Color("green")) //用于您在Assets.xcassets中创建的颜色

或者你可以用Command+Click在元素上改变它。

希望能有所帮助:)

填充整个屏幕:

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

要制作一个中央/可重用的后台小部件,您可以这样做-

import SwiftUI
struct BgView<Content>: View where Content: View {
        private let content: Content
    
        public init(@ViewBuilder content: () -> Content) {
            self.content = content()
        }
    
        var body : some View {
            ZStack {
              Color.black.ignoresSafeArea()
                content
            }
          } 
    }

并且可以像下面这样轻松地在所有视图中使用-

import SwiftUI

struct TestView: View {
    var body: some View {
      BgView{
        Text("Hello, World!")
      }.foregroundColor(.white)
    }
}

struct TestView_Previews: PreviewProvider {
    static var previews: some View {
        TestView()
    }
}

Swift UI中场景委托上的代码

内容查看background-color

window.rootViewController ? .view。backgroundColor = .lightGray

列表:

所有SwiftUI的列表都是由uitableview iOS支持的。所以你需要改变tableView的背景颜色。但由于Color和UIColor值略有不同,你可以去掉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)
    }
}

现在你可以使用你想要的任何背景(包括所有颜色)


首先看看这个结果:

正如你所看到的,你可以像这样设置视图层次结构中每个元素的颜色:

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或尝试伪造这些视图(不推荐)。