swiftxcodeuitableviewxcode13uitableviewsectionheader

Header Cell of UITableView in Swift


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?


Solution

  • 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"