0

I am using a UITableView with the header. For the header I use viewForHeaderInSection. I have a label and a button in my header cell. I also have an array to give my headerViewCell's label a name. My array is

let cellArray = ["Cat", "Dog", "Mouse", "Girraffe", "Zebra"]  

I am adding an @objc function for the headerViewCell's button and using the tag for the button.

Here is my code:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let headerView = tableView.dequeueReusableCell(withIdentifier: "HeaderTableViewCell") as! HeaderTableViewCell

    headerView.cellLabel.text = self.cellArray[section]
    headerView.cellButton.tag = section
    headerView.cellButton.addTarget(self, action: #selector(expandRow(sender:)), for: .touchUpInside)

    return headerView
}

My question is I want to change the cellLabel in the @objc func of the selected Cell. Let suppose I tap on 1st cell, I want to change the 1st cell Label Name but don't know how to do it.

This was easy if we are using the rows instead of headers as there is cellForRowAt for the rows. But I am not able to access that selected header cell.

Does anyone have the solution?

Shabnam Siddiqui
  • 579
  • 4
  • 13
Taimoor Arif
  • 750
  • 3
  • 19

3 Answers3

0

Make cellArray as var

var cellArray = ["Cat", "Dog", "Mouse", "Girraffe", "Zebra"]  

Then inside @objc function change the model

cellArray[tag] = //// new content
tableView.reloadData()
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • I also have an image in my header cell. The image is saved in my assets. What to do if I have to change image of the selected cell? – Taimoor Arif Dec 24 '21 at 07:13
0
@IBAction func expandRow(_ sender: UIButton)
{
    cellArray[sender.tag] = "new value"
    tableView.reloadData()
}
Shabnam Siddiqui
  • 579
  • 4
  • 13
  • I also have an image in my header cell. The image is saved in my assets. What to do if I have to change image of the selected cell? – Taimoor Arif Dec 24 '21 at 07:13
0

I got the answer on my own. This is what I am doing in the @objc func:


let cell = tableView.cellForRow(at: sender.section) as? HeaderTableViewCell

cell.cellLabel.text = "monkey"

Taimoor Arif
  • 750
  • 3
  • 19