![](/img/trans.png)
[英]How to move .listRowBackground style from the list to list element in SwiftUI?
[英]listRowBackground removes selection style
在 SwiftUI List
上使用listRowBackground
時,所選項目不再突出顯示。 對NavigationLink
使用ButtonStyle
也不起作用。
對此有任何理智的解決方法嗎?
示例代碼:
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())
}
}
}
盡管 Apple 的文檔中沒有記錄,但設置.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)
}
}
}
}
這是在行動:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.