【发布时间】:2016-02-13 20:29:15
【问题描述】:
您好,我有一个动态原型 TableView。我添加了 4 个原型单元。三是静态的,一是动态的。问题是我得到 Array index out of range 错误。你能检查一下出了什么问题吗?我应该分配的总行数应该是多少
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;
}
【问题讨论】:
-
仅供参考,Apple 在他们的 Swift 文档中注释常量应该反转骆驼大小写.....不是全部大写。这真的只是一个 C 的东西:/。为您的行检查使用 switch case,这将清理您的代码.. 很多。
-
仍然损坏,更新后的逻辑正在尝试访问超出范围的索引 3,4 和 5。试试
labels[indexPath.row - NUMBER_OF_STATIC_CELLS]。同时更改>= 3 to >= NUMBER_OF_STATIC_CELLS。还有@TheCodingArt 所说的关于常量大小写的内容 -
另外,我强烈建议您付出更多努力以保持缩进一致 - 如果不这样做,您只会让自己更难 - 您所有的
if都应该缩进同一级别 - 对于扫描您的代码的人来说,看起来您已经嵌套了ifs,而您却没有 -
@RichTolley 好的谢谢它的工作。你能发表你的评论作为答案吗
-
您应该接受并支持 @JulianKról 的回答 - 他的建议包含了我错过的
if声明的详细信息
标签: ios swift uitableview