SwiftUI列表。如何将圆角矩形作为列表中选定行的指示器

4

我有一个使用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))

这将产生如下图片所示的列表:

输入图像描述

但我不想让选定的元素是那个硬矩形。我想让选定的元素是圆角的,就像这样:

输入图像描述

我尝试用以下代码替换了listRowBackground

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

注意:我已将矩形的颜色更改为红色,以说明问题。

最终结果是一个红色圆角矩形覆盖在一个硬边的橙色矩形上。噢,还有红色矩形覆盖了文字。

listRowBackground不应该是背景吗?它怎么会覆盖文字呢?

我该如何做到想要的效果呢?

1个回答

7

这里是可能解决方案的演示。已在Xcode 12 / iOS 14上进行测试。

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

mask是什么鬼?真是太棒了!为什么在这种情况下需要使用Group? - Duck

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