ios - 从 2 个不同的数组加载 tableview

标签 ios swift uitableview core-data

我有 2 个核心数据数组。一个有 3 个元素,另一个也有 3 个元素。现在我想在我的 TableView 中加载这两个数组。所以我的 tableview 中总共有 6 行。

我是这样实现的...

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let totalCount = (customerDetails.count) + (customerDetails2.count)
    return totalCount
}

这两个数组的数据我尝试像这样加载到 cellForRowAt...

    let customers = customerDetails[indexPath.row]   //CRASHES HERE
    for i in 0..<(customerDetails.count) {
        cell.nameLabel.text = customers.fname
        if i == customerDetails.count {
            break
        }
    }
    let customers2 = customerDetails2[indexPath.row] 
    for i in 0..<(customerDetails2.count) {
        cell.nameLabel.text = customers2.fname
        if i == customerDetails2.count {
            break
        }
    }

但它在提到的那行崩溃说 Index out of range 可能是因为 customerDetails 只有 3 行,而加载的总单元格是 6。

在这种情况下可以做什么......?

最佳答案

if indexPath.row < customerDetails.count
{
    // load from customerDetails array
    let customer = customerDetails[indexPath.row]
}
else
{
   // load from customerDetails2 array
   let customer = customerDetails2[indexPath.row - customerDetails.count]
}

关于ios - 从 2 个不同的数组加载 tableview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48748462/

相关文章:

ios - 设置两个变量后如何调用方法

ios 第一个单元格不是从 UITableView 的顶部开始的

ios - 如何优化过滤器性能 CIFilter

ios - 可以将应用程序发布到 iTunes 连接 Mac OS Mojave 吗?

ios - 从 String Swift 2 Issue 获取数字

ios - 当我实现 UITableViewRowAction 时,为什么所有节标题行都随表格单元格一起滑动

ios - 将参数传递给 Swift 中的选择器函数

ios - UITableView 单元格重复

ios - 在 Swift 中关闭模态呈现的 View Controller 后,如何重新加载 ViewController?

ios - iOS应用程序中的订阅必需