如何编写NSOutlineView?

问题描述 投票:0回答:2

我在 Xcode 8 (Swift 3) 中创建 NSOutlineView 时遇到问题。我有一个 plist 文件,其中包含一些我想在 OutlineView 中呈现的信息。 plist 文件如下所示(示例):

Root                      Dictionary    *(1 item)
    Harry Watson          Dictionary    *(5 items)*
        name              String        Harry Watson
        age               Int           99
        birthplace        String        Westminster
        birthdate         Date          01/01/1000
        hobbies           Array         *(2 items)*
            item 0        String        Tennis
            item 1        String        Piano

OutlineView 应该看起来非常相似,如下所示:

name            Harry Watson
age             99
birthplace      Westminster
birthdate       01/01/1000
> hobbies       ...             (<- this should be expandable)

我已经在 Google 上搜索了 NSOutlineView 教程,但我找到的所有内容都是 raywenderlich.com,所以我读了一点,但在我看来这并不那么容易。 所以我想知道你是否可以帮助我完成上面的确切示例并给我一些代码示例,特别是关于此功能的代码示例:

func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {}

我不知道该写什么。

如果您有任何疑问,请告诉我。

提前致谢并致以亲切的问候

swift xcode macos plist nsoutlineview
2个回答
35
投票

我发现 Ray Wenderlitch 的教程质量参差不齐。那些笑话、冗长的内容、假设你对 Swift 一无所知的逐步指导对我来说太恶心了。这是一个简短的教程,涵盖了手动和通过 Cocoa Bindings 填充大纲视图的基础知识。


理解

NSOutlineView
的关键是你必须给每一行一个唯一的标识符,可以是字符串、数字,也可以是代表该行的对象。
NSOutlineView
称之为
item
。基于此
item
,您将查询数据模型以填充大纲视图。

这个答案提出了 3 种方法:

  1. 手动:以最基本的方式自己做所有事情。这是学习如何与
    NSOutlineView
    交互的一个很好的介绍,但我不建议将其用于生产代码。
  2. 精简:大纲视图仍然是手动填充的,但方法更加优雅。这就是我自己的生产代码所使用的。
  3. Cocoa Binding:Mac OS X 黄金时代留下的一些神奇的东西。虽然非常方便,但它不是未来的方式。将此视为高级主题

1.手动填充大纲视图

界面生成器设置

我们将使用一个非常简单的

NSOutlineView
,只有两列:键和值。

选择第一列并将其标识符更改为

keyColumn
。然后选择第二列并将其标识符更改为
valueColumn
:

Set the identifier for the Key column. Repeat for the Value column

将单元格的标识符设置为

outlineViewCell
。您只需要做一次。 Set the identifier for the cell

代码

将以下内容复制并粘贴到您的

ViewController.swift

// Data model
struct Person {
    var name: String
    var age: Int
    var birthPlace: String
    var birthDate: Date
    var hobbies: [String]
}

class ViewController: NSViewController {
    @IBOutlet weak var outlineView: NSOutlineView!

    // I assume you know how load it from a plist so I will skip
    // that code and use a constant for simplicity
    let person = Person(name: "Harry Watson", age: 99, birthPlace: "Westminster",
                        birthDate: DateComponents(calendar: .current, year: 1985, month: 1, day: 1).date!,
                        hobbies: ["Tennis", "Piano"])

    let keys = ["name", "age", "birthPlace", "birthDate", "hobbies"]

    override func viewDidLoad() {
        super.viewDidLoad()
        outlineView.dataSource = self
        outlineView.delegate = self
    }
}

extension ViewController: NSOutlineViewDataSource, NSOutlineViewDelegate {

    // You must give each row a unique identifier, referred to as `item` by the outline view
    //   * For top-level rows, we use the values in the `keys` array
    //   * For the hobbies sub-rows, we label them as ("hobbies", 0), ("hobbies", 1), ...
    //     The integer is the index in the hobbies array
    //
    // item == nil means it's the "root" row of the outline view, which is not visible
    func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
        if item == nil {
            return keys[index]
        } else if let item = item as? String, item == "hobbies" {
            return ("hobbies", index)
        } else {
            return 0
        }
    }

    // Tell how many children each row has:
    //    * The root row has 5 children: name, age, birthPlace, birthDate, hobbies
    //    * The hobbies row has how ever many hobbies there are
    //    * The other rows have no children
    func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
        if item == nil {
            return keys.count
        } else if let item = item as? String, item == "hobbies" {
            return person.hobbies.count
        } else {
            return 0
        }
    }

    // Tell whether the row is expandable. The only expandable row is the Hobbies row
    func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
        if let item = item as? String, item == "hobbies" {
            return true
        } else {
            return false
        }
    }

    // Set the text for each row
    func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
        guard let columnIdentifier = tableColumn?.identifier.rawValue else {
            return nil
        }
    
        var text = ""
    
        // Recall that `item` is the row identiffier
        switch (columnIdentifier, item) {
        case ("keyColumn", let item as String):
            switch item {
            case "name":
                text = "Name"
            case "age":
                text = "Age"
            case "birthPlace":
                text = "Birth Place"
            case "birthDate":
                text = "Birth Date"
            case "hobbies":
                text = "Hobbies"
            default:
                break
            }
        case ("keyColumn", _):
            // Remember that we identified the hobby sub-rows differently
            if let (key, index) = item as? (String, Int), key == "hobbies" {
                text = person.hobbies[index]
            }
        case ("valueColumn", let item as String):
            switch item {
            case "name":
                text = person.name
            case "age":
                text = "\(person.age)"
            case "birthPlace":
                text = person.birthPlace
            case "birthDate":
                text = "\(person.birthDate)"
            default:
                break
            }
        default:
            text = ""
        }
    
        let cellIdentifier = NSUserInterfaceItemIdentifier("outlineViewCell")
        let cell = outlineView.makeView(withIdentifier: cellIdentifier, owner: self) as! NSTableCellView
        cell.textField!.stringValue = text
    
        return cell
    }
}

结果

NSOutlineView


2.更精简的方法

按照#1 设置故事板。然后将以下代码复制并粘贴到您的视图控制器中:

import Cocoa

/// The data Model
struct Person {
    var name: String
    var age: Int
    var birthPlace: String
    var birthDate: Date
    var hobbies: [String]
}

/// Representation of a row in the outline view
struct OutlineViewRow {
    var key: String
    var value: Any?
    var children = [OutlineViewRow]()
    
    static func rowsFrom( person: Person) -> [OutlineViewRow] {
        let hobbiesChildren = person.hobbies.map { OutlineViewRow(key: $0) }
        return [
            OutlineViewRow(key: "Age", value: person.age),
            OutlineViewRow(key: "Birth Place", value: person.birthPlace),
            OutlineViewRow(key: "Birth Date", value: person.birthDate),
            OutlineViewRow(key: "Hobbies", children: hobbiesChildren)
        ]
    }
}

/// A listing of all available columns in the outline view.
///
/// Since repeating string literals is error prone, we define them in a single location here.
/// The literals must match the column identifiers in the Story Board
enum OutlineViewColumn: String {
    case key = "keyColumn"
    case value = "valueColumn"
    
    init?(tableColumn: NSTableColumn) {
        self.init(rawValue: tableColumn.identifier.rawValue)
    }
}


class ViewController: NSViewController {
    @IBOutlet weak var outlineView: NSOutlineView!
    
    let person = Person(name: "Harry Watson", age: 99, birthPlace: "Westminster",
                        birthDate: DateComponents(calendar: .current, year: 1985, month: 1, day: 1).date!,
                        hobbies: ["Tennis", "Piano"])
    var rows = [OutlineViewRow]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.rows = OutlineViewRow.rowsFrom(person: self.person)
        outlineView.dataSource = self
        outlineView.delegate = self
    }
}

extension ViewController: NSOutlineViewDataSource, NSOutlineViewDelegate {
    
    /// Return the item representing each row
    /// If item == nil, it is the root of the outline view and is invisible
    func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
        switch item {
        case nil:
            return self.rows[index]
        case let row as OutlineViewRow:
            return row.children[index]
        default:
            return NSNull()
        }
    }
    
    /// Return the number of children for each row
    func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
        switch item {
        case nil:
            return self.rows.count
        case let row as OutlineViewRow:
            return row.children.count
        default:
            return 0
        }
    }
    
    /// Determine if the row is expandable
    func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
        switch item {
        case let row as OutlineViewRow:
            return !row.children.isEmpty
        default:
            return false
        }
    }
    
    /// Return content of the cell
    func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
        guard let row = item as? OutlineViewRow,
              let column = OutlineViewColumn(tableColumn: tableColumn!)
        else {
            fatalError("Invalid row and column combination")
        }
        
        let text: String
        switch column {
        case .key:
            text = row.key
        case .value:
            text = row.value == nil ? "" : "\(row.value!)"
        }
        
        let identifier = NSUserInterfaceItemIdentifier("outlineViewCell")
        let view = outlineView.makeView(withIdentifier: identifier, owner: self) as! NSTableCellView
        view.textField?.stringValue = text
        
        return view
    }
}

3.使用 Cocoa 绑定

填充大纲视图的另一种方法是使用 Cocoa Bindings,它可以显着减少需要编写的代码量。然而,Cocoa Bindings 是一个高级主题。当它起作用时,它就像魔法一样,但当它不起作用时,它可能很难修复。 Cocoa Bindings 在 iOS 上不可用。

代码

对于这个例子,让我们加大赌注,让

NSOutlineView
显示多个人的详细信息。

// Data Model
struct Person {
    var name: String
    var age: Int
    var birthPlace: String
    var birthDate: Date
    var hobbies: [String]
}

// A wrapper object that represents a row in the Outline View
// Since Cocoa Binding relies on the Objective-C runtime, we need to mark this
// class with @objcMembers for dynamic dispatch
@objcMembers class OutlineViewRow: NSObject {
    var key: String                 // content of the Key column
    var value: Any?                 // content of the Value column
    var children: [OutlineViewRow]  // set to an empty array if the row has no children

    init(key: String, value: Any?, children: [OutlineViewRow]) {
        self.key = key
        self.value = value
        self.children = children
    }

    convenience init(person: Person) {
        let hobbies = person.hobbies.map { OutlineViewRow(key: $0, value: nil, children: []) }
        let children = [
            OutlineViewRow(key: "Age", value: person.age, children: []),
            OutlineViewRow(key: "Birth Place", value: person.birthPlace, children: []),
            OutlineViewRow(key: "Birth Date", value: person.birthDate, children: []),
            OutlineViewRow(key: "Hobbies", value: nil, children: hobbies)
        ]
        self.init(key: person.name, value: nil, children: children)
    }
}

class ViewController: NSViewController {
    let people = [
        Person(name: "Harry Watson", age: 99, birthPlace: "Westminster",
                birthDate: DateComponents(calendar: .current, year: 1985, month: 1, day: 1).date!,
                hobbies: ["Tennis", "Piano"]),
        Person(name: "Shelock Holmes", age: 164, birthPlace: "London",
               birthDate: DateComponents(calendar: .current, year: 1854, month: 1, day: 1).date!,
                hobbies: ["Violin", "Chemistry"])
    ]

    @objc lazy var rows = people.map { OutlineViewRow(person: $0) }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

界面生成器设置

在你的故事板中:

  • 从对象库添加树控制器
  • 选择树控制器并打开属性检查器 (
    Cmd + Opt + 4
    )。将其子键路径设置为
    children
  • 打开绑定检查器 (
    Cmd + Opt + 7
    ) 并为 IB 对象设置绑定,如下所示。

Tree Controller's Attributes

| IB Object       | Property           | Bind To         | Controller Key  | Model Key Path    |
|-----------------|--------------------|-----------------|-----------------|-------------------|
| Tree Controller | Controller Content | View Controller |                 | self.rows         |
| Outline View    | Content            | Tree Controller | arrangedObjects |                   |
| Table View Cell | Value              | Table Cell View |                 | objectValue.key   |
| (Key column)    |                    |                 |                 |                   |
| Table View Cell | Value              | Table Cell View |                 | objectValue.value |
| (Value column)  |                    |                 |                 |                   |

(不要将 Table View Cell 与 Table Cell View 混淆。我知道,命名很糟糕)

结果

NSOutline View with Cocoa Bindings

您可以在两种方法中使用

DateFormatter
获得更好的日期输出,但这对于这个问题来说并不是必需的。


0
投票

一个清晰的示例,非常适合作为使用 NSOutlineView 的开始。
当我使用更高版本的 Swift 时,我必须进行更改

switch (columnIdentifier, item)

switch (columnIdentifier.rawValue, item)
.

Interface Builder 也对设置进行了正确的调整

let cell = outlineView.make(withIdentifier: "outlineViewCell", owner: self) as! NSTableCellView

let cell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "outlineViewCell"), owner: self) as! NSTableCellView

© www.soinside.com 2019 - 2024. All rights reserved.