Search code examples
watchkitswiftui

How to add cornerRadius to SwiftUI List Cell when using .listRowBackground in watchOS?


I'm trying to get the normal List on the watch with a listRowBackground image on each cell.

But when I set a image as the listRowBackground the corner radius from the standard List disappears (see below).

I've tried to set the background modified in the Cell-View itself, but that results in the same problem. Looking at the Visual View Debugger it seems that the background image, extends well beyond the cell itself.

struct ListView: View {
    @ObservedObject var model: ListModel

    var body: some View {
        List {
            ForEach(self.model.items) { item in
                NavigationLink(destination: PlayerView(item: item)) {
                    ListCell(item: item).frame(height: 100)
                }
                .listRowBackground(Image(uiImage: item.image)
                .resizable()
                .scaledToFill()
                .opacity(0.7)
                )
            }
        }
        .listStyle(CarouselListStyle())
        .navigationBarTitle(Text("Today"))

    }
}

@available(watchOSApplicationExtension 6.0, *)
struct ListCell: View {
    var item: ListItem

    var body: some View {
        VStack(alignment: .leading) {
            Text("\(self.item.length) MIN . \(self.item.category)")
                .font(.system(.caption, design: .default))
                .foregroundColor(.green)
                .padding(.horizontal)
                .padding(.top, 2)
            Text(self.item.title)
                .font(.headline)
                .lineLimit(2)
                .padding(.horizontal)
        }
    }
}

Image: with background image:

w/ background image

Image: without background image:

w/o background image


Solution

  • I figured it out!

    I wrapped the image inside of a GeometryReader and added clipped() and cornerRadius(10) to the GeometryReader.

    And add buttonStyle(PlainButtonStyle()) to the NavigationLink.

        private func backgroundImage() -> some View {
            return GeometryReader { g in
                Image(<image>)
                    .resizable()
                    .blur(radius: 2)
                    .scaledToFill()
                    .frame(width: g.size.width, height: g.size.height)
            }
            .clipped()
            .cornerRadius(10)
        }
    

    and then add .listRowBackground(self.backgroundImage()) to the NavigationLink.