gpt4 book ai didi

arrays - 在 UITableview swift 中使用两个数组

转载 作者:行者123 更新时间:2023-11-28 10:37:03 24 4
gpt4 key购买 nike

我在一个单元格中有两个标签,在一个 TableView 中有两个数组,我想用标签链接每个数组

list [ ] 与 la_view 和 list_2 [ ] 与 la_view2 ,在 TableView 的一个单元格中还有 la_view 和 la_view2

运行程序时显示Error As shown .

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()
}

最佳答案

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

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 变量名。

关于arrays - 在 UITableview swift 中使用两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53034854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com