你好我有一個動態原型TableView。我添加了4個原型單元。三個是靜態的,一個是動態的。問題是我得到數組索引超出範圍錯誤。你能否檢查一下哪裏出了問題。什麼應該是行的總數,我應該分配致命錯誤:數組索引超出範圍在TableView
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;
}
FYI,蘋果在他們的Swift文件註釋常數應該顛倒駱駝情況.....並非所有帽。這只是一個C的東西:/。爲你的行檢查使用開關盒,這將清理你的代碼..很多。 – TheCodingArt
仍舊損壞,更新後的邏輯嘗試訪問索引3,4和5,這些索引超出了範圍。嘗試'標籤[indexPath.row - NUMBER_OF_STATIC_CELLS]'。還要將'> = 3更改爲> = NUMBER_OF_STATIC_CELLS'。另外,@TheCodingArt關於常量情況的說法 –
另外,我強烈建議你花更多的努力來保持縮進的一致性 - 當你不這樣做時,讓自己變得更難 - 你所有的if都應該縮進同一級別 - 掃描你的代碼的人看起來像你嵌套'ifs'當你不 –