问题描述
如何将 List
的灰色背景设置为完全透明以让红色通过?
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())
}
}
}
}
}