Swift:在 tableView Cell 中设置标签和自定义参数

Posted

技术标签:

【中文标题】Swift:在 tableView Cell 中设置标签和自定义参数【英文标题】:Swift: Set label & custom parameters in 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

的变量

【问题讨论】:

【参考方案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 数组中获取关联的项目。

【讨论】:

以上是关于Swift:在 tableView Cell 中设置标签和自定义参数的主要内容,如果未能解决你的问题,请参考以下文章

如何在 TableView Cell 中设置随机图像

Swift 4 TableView Cell 不显示正确的图像

swift TableView Cell Dequeue Trick

如何在 swift 4 中的 tableView Cell 中创建 collectionview? [复制]

如何在tableView swift的Xib Cell中创建内部视图动态

TableView Cell里面的swift CollectionView