Reputation: 47
I have Two labels in one cell and two arrays in one table view , I want to link Each array with label
list [ ] with la_view and list_2 [ ] with la_view2 , also la_view and la_view2 in one cell in table view
When running the program shows 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()
}
Upvotes: 0
Views: 1307
Reputation: 285280
Don't do that. Don't use multiple arrays as data source
return list.count + list_2.count
causes the error because actually you have only list.count
number of items where list.count
must be equal to list_2.count
. The addition raises an out-of-range exception at row list.count + 1
Use a custom struct
struct Item {
let foo : String
let bar : String
}
Then map the two arrays
var items = [Item]()
items = zip(list, list_2).map{ Item(foo:$0.0, bar:$0.1) }
In numberOfRowsInSection
return items.count
In cellForRowAt
get the value from the Item
instance
let item = items[indexPath.row]
cell.la_view.text = item.foo
cell.la_view2.text = item.bar
To append an item use
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)
}
And please according to the naming convention use lowerCamelCased rather than snake_cased variable names.
Upvotes: 3