ios - fatal error : index out of range tableview with two sections

标签 ios swift uitableview firebase firebase-realtime-database

我正在尝试使用两个 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/

相关文章:

swift 2.0,UITableView : Fetch index of 'checked' rows

swift - 一个 View Controller 中的两个 TableView ,swift

ios - 在 ios 中检测 ScrollView 内按钮上的触摸

iphone - 如何从 callOutAccessoryControlTapped : method 将数据发送到详细 vc

ios - webRTC 中对等连接状态始终保持在 "RTCICEConnectionChecking"状态

ios - 在 iOS 静态库中公开方法

ios - Google 云计算在后台使用 Swift 推送通知

swift - swift 中的动画在一些 Action 后恢复

ios - 在 Realm Swift 中声明一个 Int 数组

ios Firebase 推送通知项目