ios - tableView 中的索引超出范围

标签 ios arrays swift uitableview cell

我试图在 TableView 中显示 2 种不同类型的数据。 videoNews 数组只有一个要显示在 indexPath.row == 1 中的元素,而 Suggested News 数组有许多要显示在 indexPath.row >= 4.介于两者之间的一切都只是标签,照原样进行。当显示来自 SuggestedNews 数组的元素时,问题就出现了,tableView 给出了 index out of range 错误,即使数组有元素并且 numberOfRowsInSection 也获得了正确数量的元素。

TableView代码

var SuggestedNews = [VideoNews]()
var videoNews = [VideoNews]()

func numberOfSections(in tableView: UITableView) -> Int {
        return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return (5 + SuggestedNews.count)
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.row == 0 {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "VideoArticleCell", for: indexPath) as? VideoArticleCell {

            let video = self.videoNews[indexPath.row]
            cell.updateUI(video: video)

            return cell
        }
    } else if indexPath.row == 1 {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "VideoFirstLabelCell") {

            return cell
        }
    } else if indexPath.row == 2 {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "VideoSubmissionCell", for: indexPath) as? VideoSubmissionCell {

            return cell
        }
    } else if indexPath.row == 3 {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "VideoSecondLabelCell") {

            return cell
        }
    } else if indexPath.row >= 4 {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "VideoSuggestionCell", for: indexPath) as? VideoSuggestionCell {

            let latest = self.SuggestedNews[indexPath.row] //Index out of range
            cell.updateUI(latest: latest)

            return cell
        }
    }
    return UITableViewCell()
}

最佳答案

如果 index.row == 4 你的代码在这一行,但你想显示数组的第一个元素;因此,您的第一个数组索引等于 0。

let latest = self.SuggestedNews[indexPath.row - 4]

如果您有 4 个单元格与 SuggestedNews 不同,则您的返回不是 return (5 + SuggestedNews.count)

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return (4 + SuggestedNews.count)
}

关于ios - tableView 中的索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48182589/

相关文章:

ios - iPhone拍摄图片.AAE文件解码调整数据

ios - 当键盘出现时移动 View 并在点击周围时再次隐藏

java - Java中的双数组初始化

arrays - Fortran:指针数组数组?

ios - 使用 https 在 iOS native 应用程序的 fiddler 中记录问题

ios - 从 UIButton 继承时,continueTrackingWithTouch 不起作用

javascript - 如何获取javascript对象数组中的值的总计

ios - 如何以编程方式将现有 GCP 存储桶集成/访问到 Firebase Swift 应用程序?

ios - 使用 "_User"从 Parse "ObjectId"类中检索用户数据

ios - 创建 UIViewController 的通用子类来管理 iOS 应用程序中的所有 UI 是一个好习惯吗?