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

SwiftUI macOS中PlainListStyle列表选中项如何添加圆角边框?

解决SwiftUI List无内边距且保留选中项圆角的方案

可以通过自定义列表项的选中背景来实现需求,具体步骤和代码如下:

  1. 使用.listStyle(.plain)去除List默认内边距,这种方式不会影响滚动指示器的正常显示;
  2. 为每个列表项添加自定义选中状态背景,模拟.listStyle(.inset)的圆角效果。

完整代码示例

struct ListView: View {
    @State var selection = 0
    
    var body: some View {
        List(selection: $selection) {
            ForEach([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17], id: \.self) { item in
                Text("This is item \(item)")
                    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
                    .background(
                        // 自定义选中时的圆角背景
                        RoundedRectangle(cornerRadius: 10)
                            .fill(Color.accentColor.opacity(0.3))
                            .opacity(selection == item ? 1 : 0)
                    )
                    .listRowInsets(EdgeInsets()) // 移除单个列表项的默认内边距
            }
        }
        .listStyle(.plain)
    }
}

#Preview {
    ListView()
}

细节调整说明

  • .listRowInsets(EdgeInsets()) 配合.listStyle(.plain),彻底移除List和列表项的所有默认内边距;
  • 圆角半径10是贴近系统.inset样式的默认值,可根据视觉需求自行修改;
  • 背景颜色使用Color.accentColor.opacity(0.3),和系统选中态视觉风格一致,也可替换为Color(UIColor.systemGray5)等更贴近原生的颜色;
  • frame(maxWidth: .infinity, maxHeight: .infinity) 确保文本区域占满列表项空间,让自定义背景能完整覆盖选中区域。

内容的提问来源于stack exchange,提问作者Lupurus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 08:53:12