【问题标题】:Using two arrays in UITableview swift在 UITableview swift 中使用两个数组
【发布时间】:2018-10-28 18:36:39
【问题描述】:

我在一个单元格中有两个标签,在一个表格视图中有两个数组,我想将每个数组与标签链接

list [ ] 与 la_view 和 list_2 [ ] 与 la_view2 , 在表格视图的一个单元格中也有 la_view 和 la_view2

程序运行时显示Error如图。

var list = [String]()
var list_2 = [String]()

func tableView (_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

      return list.count + list_2.count

}

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell_1") as! TableView_Cell
        print("\(list.count)")
        cell.la_view.text = list[indexPath.row]
        cell.la_view2.text = list_2[indexPath.row] // eroor here
        cell.backgroundColor = UIColor(named: "Defeult")
        return cell
}

// This append in arrays
func append(add:Int) {
    list.append("\(add)")
    list_2.append("\(add)")
    let indexPath = IndexPath(row: list.count - 1, section: 0)
    let indexPath2 = IndexPath(row: list_2.count - 1, section: 0)
    table_View.beginUpdates()
    table_View.insertRows(at: [indexPath], with: .automatic)
    table_View.insertRows(at: [indexPath2], with: .automatic)
    table_View.endUpdates()
}

【问题讨论】:

  • 错误是什么?

标签: arrays swift uitableview


【解决方案1】:

不要那样做。不要使用多个数组作为数据源

return list.count + list_2.count

导致错误,因为实际上您只有list.count 的项目数,其中list.count 必须等于list_2.count。添加在第list.count + 1 行引发了一个超出范围的异常

使用自定义结构

struct Item {
    let foo : String
    let bar : String
}

然后映射两个数组

var items = [Item]()

items = zip(list, list_2).map{ Item(foo:$0.0, bar:$0.1) }

numberOfRowsInSection 返回items.count

cellForRowAt 中从Item 实例中获取值

let item = items[indexPath.row]
cell.la_view.text = item.foo
cell.la_view2.text = item.bar

要附加一个项目使用

func append(add:Int) {
    let lastIndex = items.count
    items.append( Item(foo:"\(add)", bar:"\(add)") )
    let indexPath = IndexPath(row: lastIndex, section: 0)
    table_View.insertRows(at: [indexPath], with: .automatic)
}

请根据命名约定使用 lowerCamelCased 而不是 snake_cased 变量名。

【讨论】:

  • 然后映射两个数组,这个写在哪里?
  • 这只是一个简单的示例,如何简单地组合数组。您应该通过直接创建 Item 实例来填充数据源数组。 Item 也是一个例子。使用更有意义的名称。
  • 我本来建议使用元组数组作为快速解决方案,但如上所述,自定义对象是可行的方法。 tableView 中的多个数组只是在询问问题,并且 indexpath 超出范围错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-18
  • 1970-01-01
  • 2016-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多