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


当前回答

解决方案:

你可以创建一个彩色视图,并将其设置为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))

结果:

其他回答

解决方案:

你可以创建一个彩色视图,并将其设置为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))

结果:

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

var body : some View{


    VStack{

        Color.blue.edgesIgnoringSafeArea(.all)

    }


}

你也可以使用ZStack:

var body : some View{


    ZStack{

        Color.blue.edgesIgnoringSafeArea(.all)

    }


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

Xcode 11.5

简单地使用ZStack添加背景颜色或图像到你的SwiftUI的主视图

struct ContentView: View {
    var body: some View {
        ZStack {
            Color.black
        }
        .edgesIgnoringSafeArea(.vertical)
    }
}

像这样

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