skip to Main Content

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?

3

Answers


  1. Chosen as BEST ANSWER

    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"
    
    

  2. Make cellArray as var

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

    Then inside @objc function change the model

    cellArray[tag] = //// new content
    tableView.reloadData()
    
    Login or Signup to reply.
  3. @IBAction func expandRow(_ sender: UIButton)
    {
        cellArray[sender.tag] = "new value"
        tableView.reloadData()
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search