Search code examples
arraysswiftuitableviewcell

Swift 5. Display array from the 2nd tableview cell ( 2nd indexpath.row )


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

Solution

  • 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])