微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SwiftUI:使插入列表背景透明?

如何解决SwiftUI:使插入列表背景透明?

如何将 List 的灰色背景设置为完全透明以让红色通过?

gray

struct ContentView: View {
    var body: some View {
        NavigationView {
            ZStack {
                Color.red
                    .ignoresSafeArea()
                vstack {
                    HStack {
                        Text("Faux Title")
                            .font(.system(.largeTitle,design: .rounded))
                            .fontWeight(.heavy)
                        Spacer()
                        Button(action: {
                            // settings
                        },label: {
                            Image(systemName: "gearshape.fill")
                                .font(.system(.title2))
                        })
                    }
                    .padding()
                    .navigationBarHidden(true)
                    
                    List {
                        Text("One")
                        Text("Two")
                        Text("Three")
                    }
                    .listStyle(InsetGroupedListStyle())
                }
            }
        }
    }
}

解决方法

在视图更改 UITableView.appearance 的 init() 中: 我们在 SwiftUI 中使用的最多的东西,例如 List 或 NavigationView,. .它们不是纯 SwiftUI,而是来自 UIKit,因此我们使用 UIKit 代码类型来更改外观。如果你记得我们应该在 UIKit 中使用这样的代码。当我们在 init 中使用 UITableView 时,我们正在访问 UITableView UIKit 的类,这意味着此更改将应用​​于我们项目中使用 List 的任何视图。

最好的方法是你正在做的方式,设置透明颜色,然后在 body 中从 SwiftUI 更改颜色!这是最方便的方式。


struct ContentView: View {
    
    init() { UITableView.appearance().backgroundColor = UIColor.clear }   // <<: here!
    
    var body: some View {
        NavigationView {
            ZStack {
                Color.red
                    .ignoresSafeArea()
                VStack {
                    HStack {
                        Text("Faux Title")
                            .font(.system(.largeTitle,design: .rounded))
                            .fontWeight(.heavy)
                        Spacer()
                        Button(action: {
                            // settings
                        },label: {
                            Image(systemName: "gearshape.fill")
                                .font(.system(.title2))
                        })
                    }
                    .padding()
                    .navigationBarHidden(true)
                    
                    List {
                        Text("One")
                        Text("Two")
                        Text("Three")
                    }
                    .listStyle(InsetGroupedListStyle())
                }
            }
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。