首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >tableView Swift中的乘积值

tableView Swift中的乘积值
EN

Stack Overflow用户
提问于 2017-08-03 08:28:02
回答 1查看 309关注 0票数 0

我希望根据字典中的行数动态地生成单元格。在视图加载时,字典为null,并在路上绑定。

字典被三个键值很好地绑定,但是当我想要根据字典值创建单元格时,键总是创建三行,并在字典中的最后一个项。

我搞不懂为什么。

这是我的密码:

代码语言:javascript
运行
复制
var peripherals = [String:String]()

   override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    print(peripherals.count)
    return peripherals.count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)

    for (peripheralDeviceUUID,peripheralDeviceName) in peripherals {
         cell.textLabel?.text = "\(indexPath) \(peripheralDeviceName) : \(peripheralDeviceUUID)"
    }


    return cell
}

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "Section \(section)"
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-03 08:51:21

从字典中生成键和值数组。

代码语言:javascript
运行
复制
    let dict = ["a": "first", "b": "second", "c": "third"]
    let arrayKeys = Array(dict.keys)
    let arrayValues = Array(dict.values)

然后在cellForRow中使用这些数组:

代码语言:javascript
运行
复制
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)    
          cell.textLabel?.text = "\(indexPath.row) \(arrayValues[indexPath.row]) : \(arrayKeys[indexPath.row])"
          return cell   
    }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45478797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档