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


当前回答

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

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

其他回答

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

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

你可以简单地改变一个视图的背景颜色:

var body : some View{


    VStack{

        Color.blue.edgesIgnoringSafeArea(.all)

    }


}

你也可以使用ZStack:

var body : some View{


    ZStack{

        Color.blue.edgesIgnoringSafeArea(.all)

    }


}

(SwiftUI / Xcode 11)

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

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

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

希望能有所帮助:)

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

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

}

这个解决方案有效吗?:

添加以下行到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
}