如何将添加到我的列表的项目具有交替背景颜色

问题描述 投票:0回答:1

我最初在列表上有交替的行背景,当这不起作用时,我尝试将它放在也不起作用的行上。我尝试过其他方法,例如使用 % mod 运算符来选择特定颜色,但这也不起作用。交替行背景最初适用于空列表。添加的项目删除了替代颜色。

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)
    }
}
user-interface swiftui interface
1个回答
0
投票

alternatingRowBackgrounds
仅适用于 macOS。

macOS 示例代码

 struct ContentView: View {
     let arr = ["item-1","item-2","item-3","item-4"]
     
     var body: some View {
         VStack {
             List(arr, id: \.self) { item in
                 Text(item)
             }
             .listStyle(.bordered)
             .alternatingRowBackgrounds()  // <--- here
             .padding(.vertical, 2)
             .listRowInsets(EdgeInsets())
             .listRowSeparator(.hidden)
         }
     }
 }
 

对于 iOS17,您可以使用

enumerated
listRowBackground
尝试不同的方法 有条件。

iOS17示例代码:

struct ContentView: View {
    let arr = ["item-1","item-2","item-3","item-4"]
    
    var body: some View {
        VStack {
            List(Array(arr.enumerated()), id: \.offset) { index, item in
                Text(item)
                    .listRowBackground(index % 2 == 0 ? Color.blue : Color.yellow)  // <--- here
            }
            .listStyle(.plain)
            .padding(.vertical, 2)
            .listRowInsets(EdgeInsets())
            .listRowSeparator(.hidden)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.