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

其他回答

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

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

NavigationView例子:

var body: some View {
    var body: some View {
        NavigationView {
            ZStack {
                // Background
                Color.blue.edgesIgnoringSafeArea(.all)

                content
            }
            //.navigationTitle(Constants.navigationTitle)
            //.navigationBarItems(leading: cancelButton, trailing: doneButton)
            //.navigationViewStyle(StackNavigationViewStyle())
        }
    }
}

var content: some View {
    // your content here; List, VStack etc - whatever you want
    VStack {
       Text("Hello World")
    }
}

填充整个屏幕:

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

像这样

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