swift - 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
应该是背景吗?它如何覆盖文本?
我该如何做我想做的事?
解决方案
这是可能解决方案的演示。使用 Xcode 12 / iOS 14 测试。
.listRowBackground(Group {
if selectedItem == item {
Color.yellow.mask(RoundedRectangle(cornerRadius: 10))
} else { Color.clear }
})
推荐阅读
- python-3.x - 如何从以下列表中获得所需的输出?
- date - 有没有办法将两种不同的 dateTime 格式解析为 Java 中的 LocalDateTime 或 Instant?
- javascript - 如何在 Electron 中使用 GET 变量重定向到另一个 HTML 文件?
- r - 如何评估字符串是否是R中的英文单词
- db2 - COBOL DB2 绑定过程
- java - Java:ClassNotFound 类路径问题
- javascript - 如何在 webgl 中用纹理相等地包裹四边形
- c# - 重新启动后自动启动 Microsoft Reporting Services
- c# - 在不退出循环 C# 的情况下验证来自控制台的输入值
- reactjs - 在功能组件中返回 React.createElement 时,“函数作为反应子无效”