SwiftUI列表使用交替的背景颜色

9
在SwiftUI中,TableView被List所代替。
有没有一种方法可以交替更改列表单元格/行的背景颜色?
我想实现像这样的东西,
if (indexPath.row % 2 == 0) { 
    aCell.backgroundColor = UIColor(red: 0, green: 1, blue: 0, alpha: 1.0) 
}

请参考文章https://medium.com/@ronm333/improving-the-appearance-of-ios-tableviews-9effb7184efb,这是一个关于改善iOS表格视图外观的好例子。

2个回答

20

这是正确的答案! - arjndr

11
我使用类似以下的代码在我的 SwiftUI 列表中交替显示背景颜色。
List {
    ForEach(items.indices) { index in
        Text(items[index])
            .listRowBackground((index  % 2 == 0) ? Color(.systemBlue) : Color(.white))
    }
}

1
如果您有一个分段控件,似乎这个解决方案存在一个苹果的 bug: "count (7) != its initial count (10). ForEach(_:content:) 应该仅用于常量数据。" - Daniel Ryan
1
有趣的是,只有在我包括 ForEach { ... } 时才起作用。 - lionello
1
这会产生“非常量范围:不是整数范围”的警告,并且仅适用于索引而不是枚举数组,但像这样在循环中添加id,就像这样ForEach(items.indices, id: \.self),可以解决问题。 - Serj Rubens

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接