我开始尝试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()
    }
}

其他回答

像这样

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

填充整个屏幕:

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

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

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

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

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

(SwiftUI / Xcode 11)

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

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

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

希望能有所帮助:)