首页 > 解决方案 > Swifui 背景颜色没有改变

问题描述

我有一个非常简单的屏幕我只需要更改屏幕的背景颜色

我的代码

struct HomeView: View {
    
    let screenWidth = UIScreen.main.bounds.size.width
    let screenHeight = UIScreen.main.bounds.size.height
    let screenSize = UIScreen.main.bounds.size
    
    var body: some View {
        
        
        VStack{
            
            Text("Hey! Welcome")
                .font(.title)
                .fontWeight(.bold)
                .foregroundColor(Color.black)
            Text("We deliver on-demand fresh fruits directly from your nearby farms.")
                .font(.body)
                .fontWeight(.medium)
                .foregroundColor(Color.gray).padding(1)
                .multilineTextAlignment(.center)
            
            Button(action: {
                
            }) {
                Text("Get Started").foregroundColor(Color.black).fontWeight(.medium).padding(10)
            }
            .frame(maxWidth: screenWidth * 0.875)
            .background(Color.yellow)
            .cornerRadius(12)
            
            
            Button(action: {
                
            }) {
                Text("I already have an account").foregroundColor(Color.black).fontWeight(.medium).padding(10)
            }
            .frame(maxWidth: screenWidth * 0.875)
            .background(Color.white)
            .cornerRadius(12)
            
            
        }
    }
}

如果我Color.purple.ignoresSafeArea()在 VStack 旁边或内部使用它会改变颜色,但我的文本等所有东西都会触底

在此处输入图像描述

我只需要更改我的背景颜色并使框透明,它显示为白色和紫色。

标签: swiftxcodeswiftui

解决方案


试试这个代码,这对我有用。

struct BackgroundClearView: UIViewRepresentable {
    func makeUIView(context: Context) -> UIView {
        let view = UIView()
        DispatchQueue.main.async {
            view.superview?.superview?.backgroundColor = .clear
        }
        return view
    }

    func updateUIView(_ uiView: UIView, context: Context) {}
}

例子:

VStack{
            GenderVW(showModal: .constant(true), selectedGender: .constant(Gender(id: 0, gender: "Male")))
        }.background(BackgroundClearView())

推荐阅读