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

如何让添加到MyList的项拥有交替背景色

问题描述
  • 给列表设置交替行背景毫无效果,尝试把该属性应用到行上也没用
  • 试过用%取模运算符指定颜色,同样无效
  • 空列表时交替背景能正常显示,但添加列表项后就消失了

初始代码

struct MyList<Content>: View where Content: View {
    @ViewBuilder let content: () -> Content
    var body: some View {
        List { content( )
            .alternatingRowBackgrounds( )
        }
        .listStyle( .bordered )
//      .cornerRadius(10)
        .padding(.vertical, 2)
        .alternatingRowBackgrounds( )
        .listRowInsets(EdgeInsets())
        .listRowSeparator(.hidden)
    }
}

编辑1:简化代码(字符串数组版)

func MyList(_ data: [String]) -> some View {
    let sortedData = data.sorted {
        $0.localizedCaseInsensitiveCompare($1) == .orderedAscending
    }

    return List {
        LazyVGrid(columns: [GridItem(.flexible())], spacing: 2) {
            ForEach(sortedData, id: \.self) { curItem in
                    HStack(spacing: 10) {
                    Text( curItem )
                    Spacer()
                }
            }
        }
    }
    .frame(maxWidth: .infinity, alignment: .leading) // 左对齐文本
    .listStyle(.bordered)
    .padding(.vertical, 2)
    .alternatingRowBackgrounds()
    .listRowInsets(EdgeInsets())
    .listRowSeparator(.hidden)
}

列表显示效果

解决方案

问题核心是你把LazyVGrid整个嵌套在了List的单个行里,alternatingRowBackgrounds()是作用在List的行级元素上的,此时List里只有一个LazyVGrid作为单行,自然不会出现交替背景。

可以用两种方式解决:

方案1:移除LazyVGrid,直接用List承载每一项

把每个列表项直接作为List的子元素,这样alternatingRowBackgrounds()就能正常作用:

func MyList(_ data: [String]) -> some View {
    let sortedData = data.sorted {
        $0.localizedCaseInsensitiveCompare($1) == .orderedAscending
    }

    return List(sortedData, id: \.self) { curItem in
        HStack(spacing: 10) {
            Text(curItem)
            Spacer()
        }
        .listRowInsets(EdgeInsets())
    }
    .frame(maxWidth: .infinity, alignment: .leading)
    .listStyle(.bordered)
    .padding(.vertical, 2)
    .alternatingRowBackgrounds()
    .listRowSeparator(.hidden)
}

方案2:保留LazyVGrid,手动实现交替背景

如果必须用LazyVGrid,可以通过ForEach的索引来判断行号,手动设置背景色:

func MyList(_ data: [String]) -> some View {
    let sortedData = data.sorted {
        $0.localizedCaseInsensitiveCompare($1) == .orderedAscending
    }

    return LazyVGrid(columns: [GridItem(.flexible())], spacing: 2) {
        ForEach(Array(sortedData.enumerated()), id: \.element) { index, curItem in
            HStack(spacing: 10) {
                Text(curItem)
                Spacer()
            }
            .background(index % 2 == 0 ? Color(.systemGray6) : Color.white)
            .frame(maxWidth: .infinity, alignment: .leading)
        }
    }
    .padding(.vertical, 2)
    .cornerRadius(10) // 按需添加圆角
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 14:56:10