如何让SwiftUI的List背景透明,仅显示自定义样式单元格?
SwiftUI List深色模式下背景透明失效的解决办法
想要让SwiftUI的List背景完全透明,只显示自定义样式的单元格,浅色模式下用.background(Color.clear)就能正常工作,但深色模式里效果不对,不知道漏了什么配置,有没有简单的实现方式?
原代码
var body: some View { ZStack { Color(.gray) .ignoresSafeArea() VStack { HStack { VStack { Text("Sheet") .textCase(.uppercase) .font(.footnote) List { ForEach(selectedSheet, id: \.self) { sheet in Text(sheet) .padding(10) .frame(maxWidth: .infinity) .background(selectedItem == sheet ? Color.blue : Color.clear) .foregroundColor(selectedItem == sheet ? Color.white : Color.primary) .cornerRadius(3) // Optional: Rounded corners for styling .onTapGesture { selectedItem = sheet // Update the selected item when clicked filteredExcel = excelData.filter { $0.sheetName == selectedItem } } } } .listStyle(PlainListStyle()) .frame(maxHeight: 150) // Limit List height if needed .background(Color.clear) .cornerRadius(10) } VStack { Text("Row") .textCase(.uppercase) .font(.footnote) List { ForEach(filteredExcel, id: \.self) { data in Text(data.column) // Use the value (or any property) of filteredData that you want to display .padding(10) .frame(maxWidth: .infinity) // Make sure the text occupies full width .cornerRadius(3) // Optional: Rounded corners for styling } } .listStyle(PlainListStyle()) .frame(maxHeight: 150) // Limit List height if needed .background(Color.clear) .cornerRadius(10) } } Spacer() } .onAppear { filteredExcel = excelData.filter { $0.sheetName == selectedItem } } } }
问题效果截图

解决办法
深色模式下List和单元格默认会保留系统背景层,只设置.background(Color.clear)无法完全清除,需要两步操作:
- 隐藏List的滚动背景层:给List添加
.scrollContentBackground(.hidden)(iOS 16+ 官方API),彻底移除List背后的系统背景。 - 清除单元格默认背景:给每个List单元格添加
.listRowBackground(Color.clear),消除单元格自带的半透明背景。
修改后的代码示例(以Sheet区域的List为例)
List { ForEach(selectedSheet, id: \.self) { sheet in Text(sheet) .padding(10) .frame(maxWidth: .infinity) .background(selectedItem == sheet ? Color.blue : Color.clear) .foregroundColor(selectedItem == sheet ? Color.white : Color.primary) .cornerRadius(3) .onTapGesture { selectedItem = sheet filteredExcel = excelData.filter { $0.sheetName == selectedItem } } .listRowBackground(Color.clear) // 清除单元格默认背景 } } .listStyle(PlainListStyle()) .frame(maxHeight: 150) .background(Color.clear) .scrollContentBackground(.hidden) // 隐藏List滚动背景 .cornerRadius(10)
把Row区域的List做同样修改即可,这样不管浅色还是深色模式,List都会完全透明,只显示你自定义的单元格样式。
兼容iOS 15及以下的方案
如果需要支持更低版本,可以在视图的init或.onAppear里全局设置UITableView外观:
UITableView.appearance().backgroundColor = .clear UITableViewCell.appearance().backgroundColor = .clear
注意这会影响全局所有的List,若需仅针对当前List生效,建议使用iOS 16+的官方API。
内容的提问来源于stack exchange,提问作者Bartender1382
相关产品推荐
相关产品推荐

