【问题标题】:Retrieve values as per index of another array根据另一个数组的索引检索值
【发布时间】:2018-06-22 12:44:44
【问题描述】:

长期以来,我一直面临着这个问题。

  • 问题:

我需要根据 tableView 中以下数组的索引获取值。

indexArray = [3, 6, 4, 5, 8, 30, 31, 7, 18, 29, 1]

paramNameArray = ["Date", "Sync Time", "UUC2T7", "Set MD", "Total KVA", "Total KW", "Running MD", "SMS 1 KW", "P.F.", "ET-5 KW", "ET-3_4 KW", "ET- 6_7 KW", "ABP-1 KW", "ABP-1A KW", "ABP-2 KW", "G-22 KW", "UUC36T37", "G-23 KW", "WRM KW", "Total KWH", "Total KVAH", "ET-5 KWH", "ET-3_4 KWH", "ET-6_7 KWH", "ABP-1 KWH", "ABP-1A KWH", "ABP-2 KWH", "SMS 1 KWH", "UUC60T73", "PLC Time", "Voltage", "Current", "Load Factor", "Avg. P.F."]

问题:

  • 现在在我的 tableView 的 cellForRowAt indexPath 中,我需要在 indexPath 0 处“设置 MD”值(需要根据 indexArray 的索引值)

这样对于tableView的每一行,我都需要根据indexArray的索引值。

例如:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{
    (at 0th Index) cell.lblParameter.text = "Set MD"  // value from paramNameArray as per indexArray's index(3)

    (at 1st Index) cell.lblParameter.text = "Running MD"  // value from paramNameArray as per indexArray's index(6) 

    // And so on...

    return cell
}

非常感谢您的帮助,谢谢! :)

【问题讨论】:

  • cell.lblParameter.text = paramNameArray[indexArray[indexPath.row]]
  • @vacawama,我不敢相信它这么简单。非常感谢你!
  • 你应该重新考虑你的数据结构。这有一种代码味道,你最终会得到一个崩溃的应用程序。
  • @AshleyMills,对不起我的英语。但我听不懂你说的。
  • 祝你好运!

标签: ios arrays swift uitableview


【解决方案1】:

首先,您需要使用cellForRowAt: 方法中的索引路径从indexArray 获取索引。然后使用该索引(从indexArray 获得)您从paramNameArray 获得价值。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let index = indexArray[indexPath.row] as! Int

//check that index won't exceeds `paramNameArray.count` otherwise it will throw `ArrayIndexOutOfBoundsException`.

  if index < paramNameArray.count {

    let text = paramNameArray[index]
    cell.lblParameter.text = text
  } else {
     cell.lblParameter.text = "some default text goes here in case if value is not present"
  }

  return cell
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-26
    • 2020-05-15
    • 1970-01-01
    • 2022-11-07
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多