获取数据到tableview

Posted

技术标签:

【中文标题】获取数据到tableview【英文标题】:Featch data to tableview 【发布时间】:2018-07-06 18:16:09 【问题描述】:

在我的第一个 vc (ViewController) 中,我有带有动作 performSegue 的按钮。在 override func prepare(for segue:) 我想将数据发送到另一个视图控制器。

这是我的代码:

if segue.identifier == "nextVC" 
        let data1 = ["TITLE", "TITLE2"]
        let data2 = ["DESCRIPTION", "DESCRIPTION 2", "DESCRIPTION 3"]
        let destination = segue.destination as! DestinationController
        destination.cellString1 = data1
        destination.cellString2 = data2
        destination.array = array

在我的第二个 vc (DestinationController) 中,我有变量 cellString1cellString2array,如下所示:

var array: [String] = []
var cellString1: [String] = []
var cellString2: [String] = []

在数组中,我发送到第一个 vc 中 tableView 单元格的第二个 vc id,如下所示:

["0", "1", "1", "0", "1"]

在第二个 vc 中,我也有带有代码的 tableView(在 tableview(cellForRowAt:) 中),如下所示:

if array[indexPath.row] == "0" 
        cell.textLabel?.text = cellString1[indexPath.row]
        cell.textLabel?.textColor = UIColor.black
        cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        cell.backgroundColor = UIColor.black
        return cell
     else if array[indexPath.row] == "1" 
        cell2.textLabel?.text = cellString2[indexPath.row]
        cell2.textLabel?.textColor = UIColor.gray
        cell2.textLabel?.font = UIFont.systemFont(ofSize: 12)
        cell2.backgroundColor = UIColor.red
        return cell2

我想检测单元格中的数组是否具有值(0 或 1),然后单元格的标签从 cellString1cellString2 获取值并显示此标签的文本。当我删除单元格 textLabel 配置时,单元格背景的颜色是正确的(black, red, red, black, red) 但是在完整代码中我在cell.textLabel?.text = cellString1[indexPath.row] 行中有错误(Index out of range)。 有可能解决吗?

【问题讨论】:

【参考方案1】:

这应该是:

    destination.cellString1 = data1
    destination.cellString2 = data2
    destination.array = array
    let destination = segue.destination as! DestinationController

您应该在destination.cellString1 = data1destination.cellString2 = data2destination.array = array 之后执行segue。否则将不会分配这些属性。

【讨论】:

【参考方案2】:

这是意料之中的,因为 3 个数组具有不同的计数,并且肯定 indexPath 将超过 cellString1,因为它包含 2 个项目,并且数组的第二个“0”在索引 3 中,超过了 cellString1 的计数

【讨论】:

【参考方案3】:

您有 2 个标题、3 个描述和 5 个颜色标志。如果您使用多个数组作为数据源,则必须确保项目数始终相同。

例如,如果您在numberOfRows 中返回array.count,那么cellForRow 会被调用5 次。但是cellString1 中的indexPath.row > 1cellString2 中的indexPath.row > 2 没有项目。这会导致超出范围的异常。

基本上,强烈建议您不要使用多个数组作为数据源。不要那样做。

使用自定义结构代替“0”和“1”字符串使用Bool

struct Item 
   var title : String
   var description : String
   var colorFlag : Bool

然后使用适当的数据创建Item 实例并传递一个数组。

【讨论】:

我正在尝试在您编写时解决我的问题,但仍然无法正常工作。我可以把我的整个代码发给你吗?

以上是关于获取数据到tableview的主要内容,如果未能解决你的问题,请参考以下文章

如何过滤获取的数据并加载到 tableview 中?

从选定的单元格获取数据(TableView)

从 TableView 中获取数据(CoreData)

通过 Alamofire,想获取数据并将其插入 TableView,但在完成插入之前,TableView 已加载

使用核心数据swift ios获取实体的所有属性到tableview中的行中的标签

使用核心数据swift ios将实体的所有属性获取到tableview中的行中的标签