【问题标题】:Thread 1: Fatal error: Index out of range, return array.count + 1线程1:致命错误:索引超出范围,返回array.count + 1
【发布时间】:2019-06-13 20:13:25
【问题描述】:

我有一个始终只有一个单元格的表格视图。如果有要从 Firebase 下载的数据,它会将其放入一个名为 posts 的数组中。例如,当用户将下载两个“在我的情况下”服务器时,它只会显示一个单元格而不是两个。我想我可以通过将return posts.count 更改为return posts.count + 1 来解决此问题,因为将始终显示一个单元格。但是如果我使用return posts.count + 1 我会得到一个

线程 1:致命错误:索引超出范围

let post = posts[indexPath.row] 行出错。我已阅读有关此错误的信息,但我似乎无法修复它。

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if posts.count == 0 {
            self.tableView.setEmptyMessage("No Servers uploaded!")
            return 1
        } else {
            self.tableView.restore()
            return posts.count
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ProfileCell", for: indexPath) as! ProfileCellTableViewCell

            cell.delegate = self
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCellMYposts

            cell.Map_image.image = nil
            let post = posts[indexPath.row]
            cell.post = post
            cell.delegate = self

            return cell
        }
    }

【问题讨论】:

  • 不要与count 属性混合,而是在posts 数组中添加一个条目,其内容为“未上传服务器!”当 firebase 请求返回一个空的结果集时。这样你就不需要任何骇人听闻的解决方案

标签: swift uitableview return tableview


【解决方案1】:

假设您在posts[0] 中有一些数据,您永远不会真正显示它。对于 indexPath.row = 0,您正在显示一个配置文件单元格,然后您开始显示来自 posts[1] 及以后的数据。将您的问题行更改为: let post = posts[indexPath.row - 1]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多