【问题标题】:Multiplied value in tableView SwifttableView Swift中的乘法值
【发布时间】:2018-01-10 17:44:33
【问题描述】:

我想根据字典中的行数动态生成单元格。在视图加载时,字典为空并绑定在路上。
字典与三个键值很好地绑定,但是当我想根据字典值和键创建单元格时,总是会在字典中的最后一项创建三行。

我不知道为什么。

这是我的代码:

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)"
}

【问题讨论】:

  • 只需删除循环并使用 indexPath.row cell.textLabel?.text = "(indexPath.row) (peripheralDeviceName) : (peripheralDeviceUUID)" 设置文本标签
  • @Ralucalonescu 你的字典里的关键字是什么?
  • 您想要根据您的字典中的值计算单元格的数量吗?正如你所说,你的字典中有 3 个键值,所以你想根据数字或键显示单元格吗?还是基于价值观?

标签: ios swift uitableview dictionary


【解决方案1】:

首先从字典中创建键和值数组。

    let dict = ["a": "first", "b": "second", "c": "third"]
    let arrayKeys = Array(dict.keys)
    let arrayValues = Array(dict.values)

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

    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   
    }

【讨论】:

    猜你喜欢
    • 2017-06-29
    • 2016-09-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多