You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 08:06:03