我有以下代码:
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
animation: .default)
private var items: FetchedResults<Item>
@State private var selectedMainItem:Item?
var body: some View {
NavigationSplitView {
List(selection: $selectedMainItem) {
ForEach(items) { item in
NavigationLink(value: item) {
Text("Item \(item.id.debugDescription)")
}
}
.onDelete(perform: deleteItems)
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
} detail: {
NavigationStack {
if let selectedMainItem = selectedMainItem {
Text("Item at \(selectedMainItem.timestamp!, formatter: itemFormatter)")
} else {
Text("Please select a main item")
}
}
}
}
private func addItem() {
withAnimation {
let newItem = Item(context: viewContext)
newItem.timestamp = Date()
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
offsets.map { items[$0] }.forEach(viewContext.delete)
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
}我只是使用默认的核心数据SwiftUI应用程序模板创建了它。然后将其转换为使用NavigationSplitView和新的NavigationLink。
在选择列表中的项时,要更改选定单元格状态的颜色。现在看起来是这样的:

我想做,所以蓝色的选择实际上是红色的。
有没有办法将选择的颜色从默认的颜色更改为我想要的任何颜色?
发布于 2022-10-05 07:23:25
您可以尝试这种方法,使用listRowBackground和selectedMainItem以及item.id。
List(selection: $selectedMainItem) {
ForEach(items) { item in
NavigationLink(value: item) {
Text("Item \(item.id.debugDescription)")
}
// -- here
.listRowBackground(selectedMainItem != nil
? (selectedMainItem!.id == item.id ? Color.red : Color.clear)
: Color.clear)
}
.onDelete(perform: deleteItems)
}https://stackoverflow.com/questions/73952070
复制相似问题