Home > database >  Header Cell of UITableView in Swift
Header Cell of UITableView in Swift

Time:12-24

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 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 has the solution?

CodePudding user response:

Make cellArray as var

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

Then inside @objc function change the model

cellArray[tag] = //// new content
tableView.reloadData()

CodePudding user response:

@IBAction func expandRow(_ sender: UIButton)
{
    cellArray[sender.tag] = "new value"
    tableView.reloadData()
}
  • Related