【问题标题】:loading tableview from 2 different arrays从 2 个不同的数组加载 tableview
【发布时间】:2018-02-12 14:12:37
【问题描述】:

我有 2 个 coredata 数组。一个有 3 个元素,另一个也有 3 个元素。现在我想在我的表格视图中加载这两个数组。所以我的表格视图中总共有 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。

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

【问题讨论】:

    标签: ios swift uitableview core-data


    【解决方案1】:
    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]
    }
    

    【讨论】:

    • 完美。请接受答案以供将来参考。
    • 当然!!所以不允许这么快接受答案......:D
    • 完全明白。去过那里:)
    • @v.bw : 我很感激
    【解决方案2】:

    您可以将两者分成两部分,而不是只创建一个部分:

    let sections = [customerDetails,customerDetails2]
    

    您可以在 numberOfSections 中提供计数:

    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }
    

    之后,在你的 numberOfItemsInSection 中你可以根据节号提供相应的数组:

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return sections[section].count
        }
    

    完成此操作后,您可以轻松访问,向 cellForRow 提供数据,如下所示:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let customer = sections[indexPath.section][indexPath.row]
         cell.nameLabel.text = customer.name
    }
    

    希望对你有帮助!!

    【讨论】:

    • 感谢您的回答...接受其他答案,因为它之前已经给出...已给予支持...:)
    • 乐于助人!! @v.bw
    • 您也可以使用 Enum 来定义每个部分,使其更具描述性。
    【解决方案3】:

    将 cellforRow 中的代码更改为此,注意

     let arr1Count = customerDetails.count
    
      if(indexPath.row < = arr1Count )
     {
         let customers = customerDetails[indexPath.row]
          cell.nameLabel.text = customers.fname
     }
    else
    
    {
         let customers = customerDetails2[indexPath.row - arr1Count]
          cell.nameLabel.text = customers.fname
    
     }
    

    【讨论】:

    • 也感谢您的贡献@Sh_Khan..已投赞成票..:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2021-08-12
    相关资源
    最近更新 更多