致命错误:TableView中的数组索引超出范围

时间:2016-02-13 20:29:15

标签: ios swift uitableview

你好,我有一个动态原型TableView。我添加了4个原型单元格。三个是静态的,一个是动态的。问题是我得到的数组索引超出范围错误。你能不能检查出了什么问题。应该分配的总行数

let NUMBER_OF_STATIC_CELLS = 3
var labels = ["label1","label2","label3"]

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


    return labels.count+NUMBER_OF_STATIC_CELLS



}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {



    var cell:  TestViewCell!

    print(indexPath.row)
    if (indexPath.row == 0) {
        cell = tableView.dequeueReusableCellWithIdentifier("static1", forIndexPath: indexPath) as! TestViewCell


    }

    if (indexPath.row == 1) {
            cell = tableView.dequeueReusableCellWithIdentifier("static2", forIndexPath: indexPath) as! TestViewCell
        //cell.cardSetName?.text = self.cardSetObject["name"] as String
        }

     if (indexPath.row == 2) {
            cell = tableView.dequeueReusableCellWithIdentifier("static3", forIndexPath: indexPath) as! TestViewCell
            //cell.cardSetName?.text = self.cardSetObject["name"] as String
        }




      if (indexPath.row >= 3) {

        cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TestViewCell
        cell.testLabel.text = labels[indexPath.row] // return test rows as set in numberOfRowsInSection
    }

    return cell;
   }

2 个答案:

答案 0 :(得分:1)

您已将单元格数设置为6,而在标签数组中您只有3个元素。此外,在您分配给单元格的每个条件中,但在方法结束时,您将覆盖(我认为)不是您的意图的分配。然后,您尝试访问超出范围的索引

下的元素

答案 1 :(得分:0)

这是你的错误!您没有索引大于2的标签。下面的行尝试标记[3]等。

cell.testLabel.text = labels[indexPath.row]