【问题标题】:How do I get both indexPath.row and indexPath.section如何同时获得 indexPath.row 和 indexPath.section
【发布时间】:2018-03-27 19:49:58
【问题描述】:

每当用户在新部分中输入内容时,先前部分的 indexpath.row 都会被该部分的新行替换。我会给你一个例子来更好地理解我想说的话:

我有一个这样的表格视图:

第 1 节:

  1. 用户输入 #1
  2. 用户输入#2

现在用户创建了一个新部分。 (第 2 节)。当他为第 2 节输入一行时,tableview 变成了

第 1 节:

  1. 用户输入#3
  2. 用户输入#2

第 2 节:

  1. 用户输入#3

用户再次添加另一个输入:

第 1 节:

  1. 用户输入#3
  2. 用户输入#4

第 2 节:

  1. 用户输入#3
  2. 用户输入#4

所以前面部分的行被新行替换。我找到了所有这些的来源,但我不知道如何解决它。问题出在这行代码:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "expenseCell") as? ExpenseCell else { return UITableViewCell() }
    let budget = userBudget[indexPath.row] // <- This
    cell.delegate = self
    cell.configureCell(budget: budget)
    return cell
}

因为只给出了 indexPath.row,而不是 indexPath.section。我的问题是,如何为 indexPath.section 和 indexPath.row 添加单元格?

我尝试修改let budget = userBudget[indexPath.row] let budget = userBudget[indexPath.section][indexPath.row] 但上面写着 Type 'Budget' has no subscript members

var userBudget : [预算] = []

Budget 是一个CoreData 实体

【问题讨论】:

标签: ios swift uitableview core-data


【解决方案1】:

问题出在您的数组中。您的数组必须是嵌套数组。

例如

var userBudget: [[Budget]] = []

如下改变你的 cellForRowAt indexPath 函数:

let budget = userBudget[indexPath.section][indexPath.row]
cell.delegate = self
cell.configureCell(budget: budget)

注意:在 userBudget 中添加“预算数组”而不是“预算”。 “预算数组”被描述为部分。

字符串数组数组的简单示例:

var userBudget: [[String]] = [
                                ["Section 1 - User input #1","Section 1 - User input #2","Section 1 - User input #3"],  //Section 1 Inputs
                                ["Section 2 - User input #1","Section 2 - User input #2"],                              //Section 2 Inputs
                                ["Section 3 - User input #1","Section 3 - User input #2"]                               //Section 3 Inputs
                             ]

【讨论】:

  • 我照你说的做了,但现在每当我添加新输入时,我的应用程序就会崩溃,说 index out of bounds
  • 这完全把我弄糊涂了。如何查看 userBudget 中有多少个数组?因为无论我给出多少输入,它始终保持为 1。
猜你喜欢
  • 2014-10-25
  • 1970-01-01
  • 2016-08-15
  • 1970-01-01
  • 1970-01-01
  • 2015-04-23
  • 1970-01-01
  • 2017-03-19
相关资源
最近更新 更多