簡體   English   中英

listRowBackground 移除選擇樣式

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM