源列表
什么是源列表?它NSOutlineView
(它是 的子类
NSTableView
)经过特殊
处理。查找器截图:
![在此处输入图像描述](https://i.stack.imgur.com/MmNH4.png)
要创建源列表,您只需将
selectionHighlightStyle
属性设置为
.sourceList
. 文档说:
NSTableView 的源列表样式。在 10.5 上,浅蓝色渐变用于突出显示选定的行。
它究竟是做什么的?跳转到Xcode 中的定义并阅读注释(未包含在文档中):
NSTableView 的源列表样式。在 10.10 及更高版本中,模糊选择用于突出显示行。在此之前,使用了浅蓝色渐变。注意:具有 drawsBackground 属性的单元格应将其设置为 NO。否则,它们将覆盖 NSTableView 所做的突出显示。设置此样式会产生将背景颜色设置为“源列表”背景颜色的副作用。此外,在 NSOutlineView 中,更改了以下属性以获得标准的“源列表”外观:indentationPerLevel、rowHeight 和 intercellSpacing。调用 setSelectionHighlightStyle: 后,可以根据需要更改任何其他属性。在 10.11 中,如果背景颜色已从“源列表”背景颜色更改为其他颜色,
由于您在 Big Sur 上,请注意SelectionHighlightStyle.sourceList
已弃用。应该使用style
& effectiveStyle
。
示例项目
代码:
- 新项目
- macOS 和应用程序(故事板和 AppKit 应用程序代表和 Swift)
- 主故事板
- 添加源列表控件
- 定位和修复约束
- 将委托和数据源设置为 ViewController
- 启用自动保存展开的项目
- 将自动保存设置为您想要的任何内容(我在
FinderLikeSidebar
那里)
- 明智地选择,因为展开状态保存在用户默认值
NSOutlineView Items FinderLikeSidebar
下
- 创造
@IBOutlet var outlineView: NSOutlineView!
- 添加另一个文本表单元格视图(无图像)
- ViewController.swift
截图
![在此处输入图像描述](https://i.stack.imgur.com/CMxMG.png)
正如你所看到的,它几乎就像 Finder - 2nd level 仍然是缩进的。原因是Documents节点是可扩展的(有子节点)。我在这里有它们来演示自动保存。
如果您想将所有 2 级节点移到左侧,只需删除它们即可。
![在此处输入图像描述](https://i.stack.imgur.com/M1Nwu.png)
ViewController.swift 代码
没什么好说的,除了 - 阅读评论:)
import Cocoa
// Sample Node class covering groups & regular items
class Node {
let id: Int
let title: String
let symbolName: String?
let children: [Node]
let isGroup: Bool
init(id: Int, title: String, symbolName: String? = nil, children: [Node] = [], isGroup: Bool = false) {
self.id = id
self.title = title
self.symbolName = symbolName
self.children = children
self.isGroup = isGroup
}
convenience init(groupId: Int, title: String, children: [Node]) {
self.init(id: groupId, title: title, children: children, isGroup: true)
}
}
extension Node {
var cellIdentifier: NSUserInterfaceItemIdentifier {
// These must match identifiers in Main.storyboard
NSUserInterfaceItemIdentifier(rawValue: isGroup ? "GroupCell" : "DataCell")
}
}
extension Array where Self.Element == Node {
// Search for a node (recursively) until a matching element is found
func firstNode(where predicate: (Element) throws -> Bool) rethrows -> Element? {
for element in self {
if try predicate(element) {
return element
}
if let matched = try element.children.firstNode(where: predicate) {
return matched
}
}
return nil
}
}
class ViewController: NSViewController, NSOutlineViewDelegate, NSOutlineViewDataSource {
@IBOutlet var outlineView: NSOutlineView!
let data = [
Node(groupId: 1, title: "Favorites", children: [
Node(id: 11, title: "AirDrop", symbolName: "wifi"),
Node(id: 12, title: "Recents", symbolName: "clock"),
Node(id: 13, title: "Applications", symbolName: "hammer")
]),
Node(groupId: 2, title: "iCloud", children: [
Node(id: 21, title: "iCloud Drive", symbolName: "icloud"),
Node(id: 22, title: "Documents", symbolName: "doc", children: [
Node(id: 221, title: "Work", symbolName: "folder"),
Node(id: 221, title: "Personal", symbolName: "folder.badge.person.crop"),
])
]),
]
override func viewWillAppear() {
super.viewWillAppear()
// Expanded items are saved in the UserDefaults under the key:
//
// "NSOutlineView Items \(autosaveName)"
//
// By default, this value is not present. When you expand some nodes,
// an array with persistent objects is saved. When you collapse all nodes,
// the array is removed from the user defaults (not an empty array,
// but back to nil = removed).
//
// IOW there's no way to check if user already saw this source list,
// modified expansion state, etc. We will use custom key for this
// purpose, so we can expand group nodes (top level) when the source
// list is displayed for the first time.
//
// Next time, we wont expand anything and will honor autosaved expanded
// items.
if UserDefaults.standard.object(forKey: "FinderLikeSidebarAppeared") == nil {
data.forEach {
outlineView.expandItem($0)
}
UserDefaults.standard.set(true, forKey: "FinderLikeSidebarAppeared")
}
}
// Number of children or groups (item == nil)
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
item == nil ? data.count : (item as! Node).children.count
}
// Child of a node or group (item == nil)
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
item == nil ? data[index] : (item as! Node).children[index]
}
// View for our node
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
guard let node = item as? Node,
let cell = outlineView.makeView(withIdentifier: node.cellIdentifier, owner: self) as? NSTableCellView else {
return nil
}
cell.textField?.stringValue = node.title
if !node.isGroup {
cell.imageView?.image = NSImage(systemSymbolName: node.symbolName ?? "folder", accessibilityDescription: nil)
}
return cell
}
// Mark top level items as group items
func outlineView(_ outlineView: NSOutlineView, isGroupItem item: Any) -> Bool {
(item as! Node).isGroup
}
// Every node is expandable if it has children
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
!(item as! Node).children.isEmpty
}
// Top level items (group items) are not selectable
func outlineView(_ outlineView: NSOutlineView, shouldSelectItem item: Any) -> Bool {
!(item as! Node).isGroup
}
// Object to save in the user defaults (NSOutlineView Items FinderLikeSidebar)
func outlineView(_ outlineView: NSOutlineView, persistentObjectForItem item: Any?) -> Any? {
(item as! Node).id
}
// Find an item from the saved object (NSOutlineView Items FinderLikeSidebar)
func outlineView(_ outlineView: NSOutlineView, itemForPersistentObject object: Any) -> Any? {
guard let id = object as? Int else { return nil }
return data.firstNode { $0.id == id }
}
}