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


当前回答

我不知道为什么没有人这么说,但是background()修饰符旨在设置背景颜色,并且支持ignoresSafeArea():

var body: some View {
    Text("Da ba dee")
        .background(Color.blue.ignoresSafeArea())
}

其他回答

这个解决方案有效吗?:

添加以下行到SceneDelegate: window.rootViewController?backgroundColor = .black

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        if let windowScene = scene as? UIWindowScene {

                window.rootViewController?.view.backgroundColor = .black
}

填充整个屏幕:

var body: some View {
    Color.green.edgesIgnoringSafeArea(.all)
}
Code Result
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)
    }
}

解决方案:

你可以创建一个彩色视图,并将其设置为VStack背景。

struct ColoredView: UIViewRepresentable {
    var color: Color
    func makeUIView(context: Context) -> UIView {
        let view = UIView()
        view.backgroundColor = UIColor(color)
        DispatchQueue.main.async {
            view.superview?.superview?.backgroundColor = .clear
        }
        return view
    }
    func updateUIView(_ uiView: UIView, context: Context) {}
}

用法:

 VStack {
    Text("VStack with Red backgound")
    Text("VStack with Red backgound")
    Text("VStack with Red backgound")
    Text("VStack with Red backgound")
 }.background(ColoredView(color: .red))

结果:

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

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)
  }

}