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


当前回答

Swift UI中场景委托上的代码

内容查看background-color

window.rootViewController ? .view。backgroundColor = .lightGray

其他回答

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

结果:

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

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在元素上改变它。

希望能有所帮助:)

你可以这样做:

.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元素