更改 SwiftUI 列表视图的背景颜色

时间:2021-03-11 16:00:22

标签: swift xcode swiftui ios14

我在 SwiftUI 中有一个视图,但没有更改背景颜色方法。我的主要代码是:

var body: some View {
        ZStack {
            Color(red: 0.17, green: 0.24, blue: 0.31)
                .edgesIgnoringSafeArea(.all)
            VStack{
                NavigationLink(destination: WelcomeView(),isActive: $isShowWelcomeView){}
                List(Modules.Modules) { module in
                    NavigationLink(destination: ModuleView(moduleName: module.name)){
                        ModuleRow(mod: module)
                    }
                }
                .navigationBarItems(trailing:
                            Button(action: {logout()}) {
                                Text("Logout")
                            })
                .navigationBarTitle("CORSO")
                .navigationBarBackButtonHidden(true)
            }
        }
    }

我的列表的通用元素是自定义元素,代码是(存储在另一个文件类中):

var body: some View {
    ZStack {
        Color(red: 0.17, green: 0.24, blue: 0.31)
                    .cornerRadius(12)
        HStack {
            VStack(alignment: .leading, spacing: 8) {
                Text(mod.name)
                    .font(.title)
                    .fixedSize(horizontal: false, vertical: true)
                    .foregroundColor(.yellow)
                Text(mod.summary)
                    .font(.caption)
                    .foregroundColor(.yellow)
            }
            Spacer()
            Image(systemName: mod.imageName)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 50, height: 50, alignment: .center)
                .padding()
                .foregroundColor(.yellow)
        }
        .padding()
        .background(Color(red: 0.17, green: 0.24, blue: 0.31))
        .listRowBackground(Color(red: 0.17, green: 0.24, blue: 0.31))
    }
    .fixedSize(horizontal: false, vertical: true)
    .shadow(color: Color.black.opacity(0.2), radius: 5, x: 0, y: 2)
}

但是,不幸的是背景颜色仍然是“白色”并且没有改变。所需的颜色是:Color(red: 0.17, green: 0.24, blue: 0.31)

这是一个运行时结果: simulator

请帮帮我!

1 个答案:

答案 0 :(得分:1)

如果您可以避免使用 LazyVStack 或 VStack,则可以轻松解决此问题,但这只是在您需要使用 List 的情况下。 请注意,这当然不是生产就绪代码,而是一种可能的解决方案或方向,如下所示。

struct ListBackgroundColorer: UIViewRepresentable {
    public func makeUIView(context: Context) -> UIView {
        
        let view = UIView()
        DispatchQueue.main.async {
            view.superview?.superview?.superview?.superview?.superview?.subviews.first(where: {NSStringFromClass(type(of: $0)) == "_UISystemBackgroundView"})?.subviews[0].backgroundColor = UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1.0)
        }
        return view
    }
    
    public func updateUIView(_ uiView: UIView, context: Context) {}
}

现在使用它作为背景。

.background(ListBackgroundColorer())

结果:

list background coloring

感谢 Asperi 的灵感。