删除/更改列表突出显示颜色(或调整项目之间的间距)



我目前正在为MacOS应用程序的SwiftUI列表制作自定义行模板。由于我没有找到删除/调整蓝色突出显示颜色的方法(我只找到了适用于iOS的解决方案(,因此我制作了以下模板,该模板涵盖了蓝色部分,但在所需区域内"模仿"了它,如下所示:屏幕截图。我设法通过使用负填充等来覆盖大部分高光颜色;但是,我只是无法摆脱项目顶部的一些蓝色像素(在屏幕截图中标记(。

我的代码如下所示:

行模板(简体版(

struct EntryRow: View {
var body: some View {

// Outer frame (white space with shadow)
ZStack(alignment: .topLeading) {

// Inner frame (actual content)
ZStack(alignment: .topLeading) {
.frame(minWidth: 0, maxWidth: .infinity)
.frame(minHeight: 0, maxHeight: .infinity)
.padding(.vertical, 0)
.background(self.model.selectedEntries.firstIndex(of: entry.id) != nil ? Color.blue : Color(NSColor.controlBackgroundColor))
// 👆🏻 Changes color according to selection state of row
.overlay(
RoundedRectangle(cornerRadius: 4)
.stroke(Color.black, lineWidth: 0)
)
.clipShape(RoundedRectangle(cornerRadius: 4))


}.padding(15)
.background(Color(NSColor.controlBackgroundColor))
// 👆🏻 Changes background color so that it corresponds to the list's background color (which achieves the white space between the items)
.shadow(color: Color(NSColor.tertiaryLabelColor), radius: 2)

}    
}

列表

行的加载方式如下:

List(selection: self.$model.selectedEntries) {
ForEach(self.model.entries, id: .id) { item in
EntryRow(entry: item)
.padding(-15)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.padding(.top, -13).padding(.horizontal, -4)

问题

有没有办法覆盖剩余的高光颜色,或者 - 更好的是 - 完全删除高光颜色?不幸的是,进一步调整填充似乎无济于事......(但也许我错过了一些东西(

提前非常感谢。

更新

选择绑定如下所示(如果相关:

class UserDataViewModel: ObservableObject {
@Published var entries = [Entry]()

@Published var selectedEntries: Set<Int32> = Set<Int32>() {
didSet {
print(selectedEntries.count)
}
}

我会建议改变一个方向......如果您不想要默认选择(您与之抗争的突出显示(,那么请不要使用它,只需点击它,就像下面的示例一样(由于提供的快照不可测试(

使用 Xcode 11.4 进行测试

struct PersonList: View {
@State var selectedPerson: String?
let persons = ["Person 1", "Person 2", "Person 3"]
var body: some View {
VStack {
Text("Selected: (selectedPerson ?? "<none>")")
List {
ForEach(persons, id: .self) { person in
VStack {
Text(person)
}.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
.background(Color(NSColor.controlBackgroundColor))
.onTapGesture {
self.selectedPerson = person
}
}
.listRowInsets(EdgeInsets())
}
}
}
}

替代:这是基于NSTableView(在 macOS 上位于List下方(通知的可能的替代

List(selection: self.$model.selectedEntries) {
ForEach(self.model.entries, id: .id) { item in
EntryRow(entry: item)
}
}
.onReceive(NotificationCenter.default.publisher(for: NSTableView.selectionIsChangingNotification)) { notification in
if let tableView = notification.object as? NSTableView {
tableView.selectionHighlightStyle = .none
}
}

最新更新