SwiftUI如何移除单元格背景色及自定义单元格相关样式?
实现方案
你需要的三个效果可以通过SwiftUI原生修饰符实现,避免全局修改UIKit外观带来的其他页面影响,具体实现逻辑如下:
- 单元格颜色:使用
listRowBackground(_:)修饰符清除系统默认单元格背景,再给行内容自定义背景色 - 单元格圆角:直接给行内容添加
cornerRadius(_:)修饰符即可自定义圆角大小 - 隐藏前两个单元格分隔线:iOS 15+ 提供的
listRowSeparator(_:edges:)可以精准隐藏第一行底部的分隔线,正好对应第一、第二行之间的分隔线
完整可运行代码如下:
struct TestView: View { init() { // 仅设置列表全局背景透明,不会影响其他控件样式 UITableView.appearance().backgroundColor = .clear } var body: some View { LinearGradient(gradient: Gradient(colors: [Color.red, Color.purple]), startPoint: .top, endPoint: .bottom) .edgesIgnoringSafeArea(.vertical) .overlay( List { Group { Text("Hallo") .frame(maxWidth: .infinity, alignment: .leading) .padding() // 自定义单元格背景色 .background(Color.green) // 自定义单元格圆角 .cornerRadius(8) // 隐藏当前行底部的分隔线,即第一、第二行之间的分隔线 .listRowSeparator(.hidden, edges: .bottom) // 清除系统默认单元格背景 .listRowBackground(Color.clear) Text("World") .frame(maxWidth: .infinity, alignment: .leading) .padding() .background(Color.green) .cornerRadius(8) .listRowBackground(Color.clear) } // 调整单元格默认内边距,可按需修改数值 .listRowInsets(EdgeInsets(top: 6, leading: 12, bottom: 6, trailing: 12)) } // 使用Plain列表样式去掉系统默认分组边距 .listStyle(.plain) .padding(50) ) } }
适配iOS13/14版本时,可以全局设置
UITableView.appearance().separatorColor = .clear隐藏全部分隔线,再给需要展示分隔线的行手动添加分割线视图即可。
效果参考图:
内容的提问来源于stack exchange,提问作者MACHINE666
相关产品推荐
相关产品推荐

