SwiftUI List . How to make a round rectangle as an indicator for a selected row on a list

Viewed 351

I have this code for a List populated by Core Data:

      List {
          ForEach(items.filter {
            self.searchText.isEmpty ? true : $0.term!.contains(self.searchText)
          }, id: \.self) { item in
            
            Button(action: {
              globalVariables.selectedItem = item                  
            }) {
              Text(item.term!)
                .font(fontItems)
                .disabled(true)
                .foregroundColor(globalVariables.selectedItem == item ? .black : .white)
            }
            .listRowBackground(
              globalVariables.selectedItem == nil ? Color(UIColor.clear) : (
                item == globalVariables.selectedItem ? Color("corListaSelecao") : Color(UIColor.clear)))
          }
          .onDelete(perform: deleteItems)
          .onAppear{
            globalVariables.selectedItem = items.first
          }
          .cornerRadius(20)
        }
        .background(Color("fundoControles"))
        .cornerRadius(10)
        .padding(EdgeInsets(top: 5, leading: 10, bottom: 5, trailing: 10))

This produces a list like the following picture:

enter image description here

But I don't want the selected element to be that hard rectangle. I want the selected element to be rounded, like this:

enter image description here

I have tried to replace the listRowBackground code with

.listRowBackground(
    RoundedRectangle(cornerRadius: 10)
      .background(globalVariables.selectedItem == nil ? Color(UIColor.clear) : (
            item == globalVariables.selectedItem ? Color.red : Color(UIColor.clear)))
)

NOTE: I have changed the rectangle color to red to illustrate the problem.

The final result is a red rounded rectangle drawn over a hard edge orange rectangle. Ah, and the red rectangle covers the text.

Isn't the listRowBackground something that should be a background? How can it cover the text?

How do I do what I want?

1 Answers

Here is a demo of possible solution. Tested with Xcode 12 / iOS 14.

.listRowBackground(Group {
    if selectedItem == item {
        Color.yellow.mask(RoundedRectangle(cornerRadius: 10))
    } else { Color.clear }
})
Related