简体   繁体   English

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

[英]fatal error: Array index out of range in TableView

hello I have a Dynamic Prototype TableView. 您好,我有一个动态原型TableView。 I have added 4 prototype cells. 我添加了4个原型单元。 Three are static and one is dynamic. 三是静态,一是动态。 The problem is I am getting Array index out of range error. 问题是我得到数组索引超出范围错误。 could you please check what went wrong. 你能检查出什么问题了吗? what should be the total number of rows should I assign 我应该分配的总行数是多少

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;
   }

You have set that number of cells will be 6 and in labels array you have only 3 elements. 您已将单元格数设置为6,并且在标签数组中只有3个元素。 Moreover in each condition you are assigning to cell but at the end of the method you are overwriting that assignment which is (I suppose) not your intention. 此外,在每种情况下,您要分配给单元格,但在方法结束时,您将覆盖该分配(我想)不是您的意图。 Then you are trying to access element under the index that is out of bounds 然后,您尝试访问超出范围的索引下的元素

This is your ERROR! 这是您的错误! You have no label with an index above 2. The line below tries to do to label[3] etc. 您没有索引大于2的标签。下面的行尝试对label [3]等进行操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM