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


当前回答

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

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

}

其他回答

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

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

var body : some View{


    VStack{

        Color.blue.edgesIgnoringSafeArea(.all)

    }


}

你也可以使用ZStack:

var body : some View{


    ZStack{

        Color.blue.edgesIgnoringSafeArea(.all)

    }


}

你可以这样做:

.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 > Your Color来使用视图的inspect元素

这个解决方案有效吗?:

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

首先,你应该使用

 ZStack {
      Color("Desired_color_name").ignoresSafeArea()
// if you create any color set then give that colour set name
// otherwise use Color.gray or as you want the colour name
    
     //Here you should start your design
    }