首页 > 解决方案 > SwiftUI 列表。如何将圆角矩形作为列表中选定行的指示器

问题描述

我有一个由核心数据填充的列表的代码:

      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应该是背景吗?它如何覆盖文本?

我该如何做我想做的事?

标签: swiftswiftui

解决方案


这是可能解决方案的演示。使用 Xcode 12 / iOS 14 测试。

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

推荐阅读