【问题标题】:Array out of range with check function带有检查功能的数组超出范围
【发布时间】:2016-10-10 15:21:40
【问题描述】:

我有一个数组和一个检查函数。

点击按钮时的功能:

// VARS
var workoutArray: [workout]!
var index = Int()

@IBAction func finishExerciseBtnPressed(_ sender: AnyObject) {

    // reload tabledata with next exercise in array

    print("the count of array is \(workoutArray.count)")

    if index <= workoutArray.count {
        index = index + 1
        tableView.reloadData()
        print("The exercise number is \(index)")
    } else {
        // Show finish workout button
        print("No items found anymore")
    }
}

tableViewdequeReusableCell的函数:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "workoutStartCell", for: indexPath) as? workoutStartCell {

        let workout = workoutArray[index]
        cell.updateUI(workout: workout, exercise: index + 1)

        return cell

    }else{
        return UITableViewCell()
    }
}

我正在从以前的viewcontroller 发送数字 0 到此 vc 顶部的索引 var。我有检查方法finishExercisePressed,但无论我在做什么,它都会一直计数低谷。它说索引超出范围,但我正在检查索引是否等于或低于数组的计数。

这是我想要达到的目标:

有人可以帮帮我吗?

非常感谢。

【问题讨论】:

  • 避免返回空单元格
  • index 代表什么?这是当前锻炼的编号吗?
  • 索引代表: - 当前锻炼的组数。我将更改名称,因为它不是一个好的命名

标签: ios arrays swift uitableview


【解决方案1】:

我正在检查索引是否等于或小于数组的计数。

没错。但是,您是在增加索引之前执行此操作的,并且由于索引从零开始,因此您应该在结束前停止一个索引:

var index = 1 // Set the index to 1 initially to skip the title
...
if index+1 < workoutArray.count {
    index += 1
    tableView.reloadData()
    ...
}

上述检查验证index 将在 递增后保持在范围内。

【讨论】:

  • 问题是我在 tableView 中显示我的结果。但标题应以 1,2,3 等开头
  • tahts 为什么我在 tableview 中递增
  • 我给你加了一张图片
  • 所以从前一个视图控制器中他得到了数字:0,但它将在生成单元格的表格视图中被覆盖。 index + 1 所以它直接在负载上得到数字 1
猜你喜欢
  • 2015-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多