Search code examples
swiftuiapple-watchvstack

Background for List Items on Apple Watch with SwiftUI


I'm working on building an Apple Watch screen in SwiftUI. The layout is working nicely, but there are aspects of the color styling that I can't seem to figure out. Here's my code:

struct Watch3ThingsMainUI: View {
    var goals: [Goal]

    var body: some View {

        VStack {
            Text("3things")
                .foregroundColor(Color("3thingsBlue"))

            List(goals) { goal in
                HStack {
                    Text(goal.name)

                    Spacer()

                    Image(systemName: "gear")
                }
                .background(Color.blue)
            }
            .background(Color.green)
            .foregroundColor(Color.red)
            .accentColor(Color.yellow)
        }
    }
}

And here's a shot of how it renders:

sample screen shot

You'll note that the HStack's blue background only covers a rectangular area, not the whole button that the List seems to create automatically. And oddly, while the List supports a background modifier, it appears to be ignored -- nothing is colored green.

What I'd love to be able to do is to determine the background for the entire button, but I can't figure a way to do so -- it remains stubbornly dark gray around the HStack no matter what shenanigans I try.


Solution

  • Try to replace your body with that can make the whole button is blue

    var body: some View {
    
        VStack {
            Text("3things")
                .foregroundColor(Color("3thingsBlue"))
            List {
                ForEach(self.goals) { goal in
                    HStack {
                        Text(goal.name)
                        Spacer()
                        Image(systemName: "gear")
                    }
                    .listRowBackground(Color.blue)
                }
            }
            .foregroundColor(Color.red)
            .accentColor(Color.yellow)
        }
    }