【问题标题】:Fetching from Core Data and display in UITableView with custom cell从核心数据中获取并使用自定义单元格在 UITableView 中显示
【发布时间】:2018-06-04 14:44:14
【问题描述】:

我有一个带有自定义单元格的 UITableView:

标题、标签、文本

这些是 UITextView 的 3 个元素,现在我的核心数据中有一个实体:

我想把标题、标题、标签中的日期和文本中的 introText:

我这样做了:

    do{
        var request = NSFetchRequest<NSFetchRequestResult>(entityName: "Actualites")
        let count  = try context.count(for: request)
        if (count == 0) {
            REST().SaveArticles(limit: 5, limitstart: 0, catid: 6, key: "xxx", context: context)
        } else {
            var actualites  = [Actualites]()
            actualites = try context.fetch(request) as! [Actualites]


            let cell:ActuTblCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! ActuTblCell

            for actualites in actualites {

                print(actualites.title)

            }
        }
    }catch{
        print(error)
    }

我可以在循环中获取标题,但是如何显示数据?我必须创建 3 个数组吗?

编辑: 我想我必须在这里做一个循环?

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


    let formatter = DateFormatter()
    formatter.dateFormat = "dd/MM/yyyy HH:mm"

    cell.titleActuCell.text = actualites[indexPath.row].title
    cell.dateActuCell.text = formatter.string(from: actualites[indexPath.row].created! as Date)
    cell.descriptionActuCell.text = actualites[indexPath.row].introText

    return cell
}

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

【问题讨论】:

    标签: swift uitableview core-data


    【解决方案1】:

    在您的视图控制器中保留Actualites: var actualites = [Actualites]() 的数组。然后你的else 块看起来像这样:

    else {
        actualites = try context.fetch(request) as! [Actualites]
        tableview.reloadData()
    }
    

    您应该实现UITableViewDataSource 协议以根据actualites 数组返回单元格的数量,并在tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) 中通过以下语句获得每个单元格的实际值:let actuality = actualites[indexPath.row] 并显示在适当的位置细胞。

    【讨论】:

    • 抱歉终于没事了:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多