Swift:如何使选定的单元格NSLog从字典中获取相应的值和键

时间:2015-01-28 02:56:05

标签: swift nsdictionary tableview

我有一个由字典填充的TableViewController。我的目标是,当我从tableView中单击一个单元格时,它将从字典中NSLog单元格的名称以及相应的值。

例如,如果我有一本字典: var profiles = ["Joe": 1, "Sam": 2, "Nancy": 3, "Fred": 4, "Lucy": 5]

当我点击Sam时,它会出现在" Sam。 2"或类似的东西。 任何帮助都会很棒。

这是我的代码示例(TableView):

class ProfileTableViewController: UITableViewController {

var person = people ()

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  let row = indexPath.row
    let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
    let myRowKey = person.typeList[row]
    let myRowData = person.profiles[myRowKey]
    cell.textLabel!.text = myRowKey

    cell.textLabel?.text = String(myRowKey)
     return cell

}


override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

   // Here's where I'm at

}

这是我的快速文件:

class people {
var profiles = ["Joe": 1, "Sam": 2, "Nancy": 3, "Fred": 4, "Lucy": 5]
var typeList:[String] { //computed property 7/7/14
    get{
        return Array(profiles.keys)
    }





    }

2 个答案:

答案 0 :(得分:1)

我会在标签中找到文本并用它来搜索字典:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

   // Get the cell for that indexPath
   var cell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell!

   // Get that cell's labelText
   let myKey = cell.textLabel?.text

   // Output the key and it's associated value from the dictionary
   println("\(myKey): \(person.typeList[myKey])")

}

答案 1 :(得分:1)

因此,理想情况下,您希望使用该方法提供的索引路径来获取所选的任何单元格。

完成后,您可以从单元格中提取文本并检查字典。

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    // Lots of optional chaining to make sure that nothing breaks
    if let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath) { // Get the cell
        if let cellTextLabel: UILabel = cell.textLabel { // Get the cell's label
            if let name: String = cellTextLabel.text { // Get the text from its label
                println("\(name): \(profiles[name])") // Check with the dictionary and print out the corresponding value
            }

        }
    }
}
相关问题