首页 > 解决方案 > 修改行背景颜色列表 SwiftUI

问题描述

我正在尝试更改列表中的行颜色。

struct ContentView: View {
@State var userProfiles : [Profile] = [Profile.default]

var body: some View {
    VStack{
    List(userProfiles.indices, id: \.self, rowContent: row(for:)).background(Color.red)
    }.background(Color.red)
}

// helper function to have possibility to generate & inject proxy binding
private func row(for idx: Int) -> some View {
    let isOn = Binding(
        get: {
            // safe getter with bounds validation
            idx < self.userProfiles.count ? self.userProfiles[idx] : DtrProfile.default
        },
        set: { self.userProfiles[idx] = $0 }
    )
    return Toggle(isOn: isOn.isFollower, label: { Text("\(idx)").background(Color.red) } )
   }
}

输出:-

截屏

我想实现:-

截屏

有人可以向我解释如何更改整行颜色。我已经尝试按上面的方法实现,但还没有结果。

任何帮助将不胜感激。

提前致谢。

标签: listswiftuirowbackground-colorswiftui-list

解决方案


利用listRowBackground

var body: some View {
    VStack{
        List {
            ForEach(0...15, id: \.self, content: row(for:)).background(Color.red).listRowBackground(Color.red)
        }
    }
}

推荐阅读