我正在尝试使用两个 Firebase 对象数组(称为快照)来填充具有 2 个部分的 tableView。当我尝试加载 tableView 时,我的 cellForRowAtIndexPath 函数出现错误:fatal error: Index out of range
。
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PersonCell", forIndexPath: indexPath) as! PersonCell
//set cell text
let guardianDict = guardians[indexPath.row].value as! [String : AnyObject] // error happens here
let dependentDict = dependents[indexPath.row].value as! [String : AnyObject]
cell.personName.text = "test"
return cell
}
以下是我如何定义我的部分:
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch(section){
case 0: return "Dependents"
case 1: return "Guardians"
default: return ""
}
}
有什么想法吗? 谢谢!
编辑:添加 numberOfSections 和 numberOfRowsInSection:
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
switch(section){
case 0: return self.dependents.count
case 1: return self.guardians.count
default: return 1
}
}
最佳答案
您的表格中有两个部分,每个部分来自不同的来源。您需要在 cellForRowatIndexPath 函数中添加检查以访问正确的数组:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PersonCell", forIndexPath: indexPath) as! PersonCell
if indexPath.section == 0
{
let dependentDict = dependents[indexPath.row].value as! [String : AnyObject]
}
else if indexPath.section == 1
{
let guardianDict = guardians[indexPath.row].value as! [String : AnyObject] // error happens here
}
cell.personName.text = "test"
return cell
}
关于ios - fatal error : index out of range tableview with two sections,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38648976/