Taimoor Arif
Taimoor Arif

Reputation: 1190

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?

Upvotes: 0

Views: 1557

Answers (3)

Taimoor Arif
Taimoor Arif

Reputation: 1190

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"

Upvotes: 0

Shabnam Siddiqui
Shabnam Siddiqui

Reputation: 614

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

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100523

Make cellArray as var

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

Then inside @objc function change the model

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

Upvotes: 0

Related Questions