【问题标题】:Displaying Different Row in Different Section in UITableView在 UITableView 的不同部分显示不同的行
【发布时间】:2021-06-24 13:08:00
【问题描述】:

我已从 API 获取此数据 - 这是接下来 7 天的天气报告。我想将其显示为表格视图,其中

  • 日期将作为部分
  • 温度(最小值/最大值)作为行

但是如果我选择这样的部分编号 -

func numberOfSections(in tableView: UITableView) -> Int {
    return myList.count  // myList is an array of containing the 7 day's data 
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

它在所有部分打印同一行(数组的第一个数据)。那么如何在不拆分数组的情况下在单独的部分打印单独的天气?

【问题讨论】:

  • 请不要显示代码图片。

标签: ios swift uitableview tableview


【解决方案1】:

UITableView中的section和rows,关键通常是二维数组。 尝试像这样创建一个二维数组:

myList[sectionItems][rowItems]

这个数组内部应该是这样的:

myList = [
 [date, minTemp, maxtemp],
 [date, minTemp, maxtemp],
 [date, minTemp, maxtemp],
 [date, minTemp, maxtemp]
]

所以您的 UITableViewDelegate 和 DataSource 函数将如下所示:

func numberOfSections(in tableView: UITableView) -> Int {
  return myList.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  return  myList[section].count
}

以上示例将允许您有 4 个部分,每个部分将有 3 行。

然后您可以在第一行打印日期,在其他行打印其余日期。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = UITableViewCell()                    
  cell.textLabel.text = myList[indexPath.section][indexPath.row]
  return cell
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多