【问题标题】:Swift: Set label & custom parameters in tableView CellSwift:在 tableView Cell 中设置标签和自定义参数
【发布时间】:2016-02-03 06:47:10
【问题描述】:

这是上一个问题的基础。

我有一个这样定义的数组:

var items = [[String:String]]()

此数据是从 json 文件动态更新的

for (_,bands) in json {
    for (_,bname) in bands {
       let bnameID = bname["id"].stringValue
       let bnameName = bname["Title"].stringValue

       let dict  = ["id":bnameID,"Title":bnameName]
       self.items.append(dict as [String : String])


       self.tableView.reloadData()

    }
}

这是我打印 items 数组时的输出

[["Title": "The Kooks", "id": "2454"], 
["Title": "The Killers", "id": "34518"], 
["Title": "Madonna", "id": "9"]] 

问题一:

在这个函数中

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { }

如何让单元格标签显示数组“标题”部分中的项目?

问题 2

在这个函数中:

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

如何从与单击的单元格对应的数组中获取值“id”?例如,如果单击 The Killers 单元格,那么我可以设置一个值为:34518

的变量

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    获取title

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
        print(items[indexPath.row]["Title"])
    }
    

    获取id

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    
        print(items[indexPath.row]["id"])
    }
    

    【讨论】:

    • 谢谢。我是如此接近,我在做: print(items["id"][indexPath.row]) :S
    • 哦! items["id"] 仅适用于 Dictionary。但是对于数组,每次都需要指定索引,所以下次请注意!
    【解决方案2】:
     func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
    
        let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath)!
        let dictn : NSDictionary = items[indexPath.section] as! NSDictionary
    
        cell.textLabel?.text = dictn.objectForKey("Title") as? String
        return cell
    }
    

    【讨论】:

      【解决方案3】:

      问题 1 的答案-

      您可以使用 indexPath 的行值获取 items 数组中项目的标题:

      let item = items[indexPath.row]
      //Fetch the id
      let title = item["Title"]!
      

      问题 2 的答案-

      let item = items[indexPath.row]
      //Fetch the id
      let id = item["id"]!
      

      因此,在任何一种情况下,您都将使用 indexPath 的行值从 items 数组中获取关联的项目。

      【讨论】:

        猜你喜欢
        • 2023-03-15
        • 1970-01-01
        • 2014-08-26
        • 2017-12-02
        • 1970-01-01
        • 1970-01-01
        • 2016-04-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多