在几个 NSTableviews 中呈现字典

Present dictionary in several NSTableviews

我是 cocoa 的初学者,我一直在尝试使用 swift 编程语言为 Mac 制作一个简单的应用程序,但我卡住了,不能'找不到解决办法。

我想在两个或多个 table 视图中显示字典中的数据,其中第一个 table 将显示键,第二个 table 将显示值。

比如我有一本字典

var worldDict:NSDictionary = ["Africa":["Egypt", "Togo"],"Europe": ["Austria", "Spain"]]

我可以在第一个 table 中显示所有大陆,但我不知道如何让第二个 table 显示我在第一个 table 中选择的大陆国家.

我的 ViewController 是两个 table 的数据源和委托。

extension ViewController: NSTableViewDataSource {
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
    if tableView == continentTable {
    return self.worldDict.valueForKey("Continent")!.count
    } else if tableView == countryTable {
        return self.worldDict.valueForKey("Continent")!.allKeys.count
    }
    return 0
} 
 func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
    var cell = tableView.makeViewWithIdentifier(tableColumn!.identifier, owner: self) as! NSTableCellView
    if tableView == self.continentTable {
    let continent: AnyObject? = wordlDict.valueForKey("Continent")
        var keys = continent!.allKeys        
    cell.textField?.stringValue = keys[row] as! String
    } else if tableView == self.countryTable {
        var countriesOfContinent: AnyObject? = worldDict.valueForKey("Continent")?.valueForKey("Africa")!
        cell.textField?.stringValue = countriesOfContinent?.allKeys[row] as! String
    }
        return cell
}

}

在这里,我在 tables 中提供了字典中的数据,但是是分开的,并且无法弄清楚如何让它们一起工作。

我也知道如何获取已选择的行数

extension ViewController: NSTableViewDelegate {

func tableViewSelectionDidChange(notification: NSNotification) {
    let continentSelected = rowSelected()
}}
func rowSelected() -> Int? {
    let selectedRow = self.continentTable.selectedRow
    if selectedRow >= 0 && selectedRow < self.worldDict.valueForKey("Continent")!.count {
        return selectedRow
    }
    return nil
}

部分问题在于您依赖 allKeys() 编辑的键 return 的顺序是可靠的,但事实并非如此。您需要保留一个单独的大洲数组。它基本上可以是一次 allKeys() returned 的副本,但你不应该每次都调用 allKeys()

numberOfRowsInTableView() 中,对于国家 table,您想要 return 所选大洲的国家数量:

} else if tableView == countryTable {
    if let selectedContinentRow = rowSelected() {
        let selectedContinent = continentsArray[selectedContinentRow]
        return self.worldDict[selectedContinent].count
    }
    return 0
}

对于 tableView(_:viewForTableColumn:row:),您想要 return 所选大洲国家/地区数组中的一个元素:

} else if tableView == self.countryTable {
    if let selectedContinentRow = rowSelected() {
        let selectedContinent = continentsArray[selectedContinentRow]
        return self.worldDict[selectedContinent][row]
    }
}

此外,每当所选大陆发生变化时,您需要告诉国家table重新加载其数据:

func tableViewSelectionDidChange(notification: NSNotification) {
    // ... whatever else ...
    let tableView = notification.object as! NSTableView
    if tableView == continentTable {
        countryTable.reloadData()
    }
}