SwiftUI:如何移除列表视图中列表项的系统自带彩色边框?
问题:SwiftUI列表项无法移除系统默认彩色边框
我已经重构代码30多次,还是完全卡在这里——不知道怎么移除列表视图中每个列表项周围的系统彩色小边框,观感特别差,想把它设为透明,但不管在哪里设置颜色参数或修饰符都没用。翻遍网站也没找到相关帖子。
问题截图:
负责列表的代码:
ZStack { if ingredients.isEmpty && colorScheme == .light { Color(.systemGray6) .cornerRadius(10) .shadow(color: Color.black.opacity(0.2), radius: 5, x: 0, y: 2) .edgesIgnoringSafeArea(.all) } else { List { ForEach(ingredients, id: \.self) { ingredient in IngredientRowView(ingredient: ingredient) { removeIngredient(ingredient) } } .onDelete { indices in ingredients.remove(atOffsets: indices) } } .listStyle(InsetGroupedListStyle()) // Add list style .background(Color.clear) .cornerRadius(10) .shadow(color: Color.black.opacity(0.2), radius: 5, x: 0, y: 2) } }
剩余代码:
struct IngredientRowView: View { let ingredient: String let onDelete: () -> Void var body: some View { HStack { Text(ingredient) .font(.body) .padding(.leading, 8) .foregroundColor(.primary) Spacer() Button(action: onDelete) { Image(systemName: "minus.circle") .resizable() .foregroundColor(.gray) .frame(width: 14, height: 14) } .buttonStyle(BorderlessButtonStyle()) } .padding(.vertical, 8) .background(VisualEffectView()) .cornerRadius(8) .padding(.horizontal, 16) .shadow(color: Color.black.opacity(0.1), radius: 4, x: 0, y: 2) } } struct VisualEffectView: UIViewRepresentable { func makeUIView(context: Context) -> UIVisualEffectView { UIVisualEffectView(effect: UIBlurEffect(style: .systemUltraThinMaterial)) } func updateUIView(_ uiView: UIVisualEffectView, context: Context) {} }
解决方案
这个问题是InsetGroupedListStyle的列表单元格默认带有背景色,和你自定义的IngredientRowView背景叠加后,就会显示出多余的边框。直接用下面两种方法解决:
方法一:针对单个列表项移除默认背景
在ForEach里的每个IngredientRowView后面添加.listRowBackground(Color.clear),直接清空系统默认的单元格背景:
ForEach(ingredients, id: \.self) { ingredient in IngredientRowView(ingredient: ingredient) { removeIngredient(ingredient) } .listRowBackground(Color.clear) // 新增这一行 }
方法二:全局设置所有列表单元格背景透明
如果你的App里多个列表都需要这个效果,在父视图的onAppear方法里添加全局配置:
.onAppear { UITableViewCell.appearance().backgroundColor = .clear }
另外可以调整IngredientRowView里的.padding(.horizontal, 16),因为InsetGroupedListStyle本身已经带有内边距,叠加后可能让布局显得冗余,根据你的视觉需求调整即可。
内容的提问来源于stack exchange,提问作者ZoomsSki
相关产品推荐
相关产品推荐

