I have a tableview with 2 prototype cells that are 3 rows. The 1st prototype cell just has a view. The 2nd prototype cell has a button. The 1st prototype cell is just 1 row which is also the first indexpath.row The 2nd prototype cell has 2 rows. ( 2nd and 3rd indexpath.row )
I want to merge my model ( array ) with the 2nd and 3rd rows. But the app crashes and said out of range.
Tableview class
let modelArray = [phone, remote]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1 modelArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
UITableViewCell {
if indexPath.row < 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "CELL1", for:
indexPath) as! CELL1
cell.view.backgroundColor = .red
return cell
}
let cell2 = tableView.dequeueReusableCell(withIdentifier: "CELL2", for: indexPath)
CELL2
This is where I am getting the out of range error. ( I tried it without the 1 as well )
cell2.configure(title: modelArray[indexpath.row 1])
return cell2
}
CELL2 class
@IBOutlet weak var buttonName: UIButton!
private var title: String = ""
func configure(title: String) {
self.title = title
buttonName.setTitle(title, for: .normal)
}
CodePudding user response:
because your modelArray have only 2 element and you are trying to get 3rd element value.
let's suppose when indexPath
is 0 then tableview
renders the CELL1 and when indexPath
is incremented, we can say it when indexPath
is 1 then your getting the value from your modelArray like below :
cell2.configure(title: modelArray[indexpath.row 1])
which is getting the value modelArray[1 1] that turns in modelArray[2] but modelArray doesn't contains modelArray[2], it has only 0 and 1 element.
try with by subtracting 1 from current indexPath
.
cell2.configure(title: modelArray[indexpath.row - 1])
CodePudding user response:
Please look at the logic: cellForRow
is called three times (1 2), but there is no item at index 3 in the array (nor at index 2 without 1
).
According to the code the cell at indexPath.row == 1
is supposed to display the first item in the array (index 0) and the cell at indexPath.row == 2
the second item (index 1).
So you have to subtract 1
cell2.configure(title: modelArray[indexpath.row - 1])