listRowBackground在 SwiftUI 上使用时,List所选项目不再突出显示。使用 aButtonStyle也NavigationLink不起作用。
对此有任何明智的解决方法吗?
示例代码:
struct ContentView: View {
struct ContentSection: Identifiable {
let id = UUID()
let title: String
let items: [String]
}
var sections = [
ContentSection(title: "Lorem", items: ["Dolor", "Sit", "Amed"]),
ContentSection(title: "Ipsum", items: ["Consectetur", "Adipiscing", "Elit"])
]
var body: some View {
NavigationView {
List {
ForEach(sections) { section in
Section {
ForEach(section.items, id: \.self) { item in
NavigationLink(destination: Text(item)) {
Text(item)
}
.listRowBackground(Color.orange.ignoresSafeArea())
}
} header: {
Text(section.title)
}
}
}
.listStyle(GroupedListStyle())
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 0
尽管苹果文档中没有记录,但设置 a.listRowBackground将明智地删除选择行为。Color.grey如果您设置与默认选择颜色相匹配的背景,会发生什么情况?苹果现在应该选择不同的颜色吗?他们如何确保对比度足够高,以便用户判断选择是否处于活动状态?
幸运的是,您可以使用以下方法实现自己的选择行为List(selection:, content:),然后将渲染的项目ForEach与当前选定的项目进行比较并自行更改背景:
struct ContentView: View {
@State var selection: Int?
var body: some View {
List(selection: $selection) {
ForEach(1...5, id: \.self) { i in
Text(i, format: .number)
.listRowBackground(i == selection ? Color.red.opacity(0.5) : .white)
.tag(i)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是在行动中:
| 归档时间: |
|
| 查看次数: |
167 次 |
| 最近记录: |