Pangu
Pangu

Reputation: 3819

How to update a custom section header without reloading the whole table view?

I have a custom header class to customize my tableview section header. On the left side of the section header is a static UILabel, while on the right side is a count UILabel to keep count of how many rows are in that particular section:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
    let headerCell = tableView.dequeueReusableCell(withIdentifier: "HeaderCell") as! CustomCell

    if section == 0
    {
        headerCell.reminder.text = "It Is Time"
        headerCell.count.text = String(arrayOne.count)
        headerCell.contentView.backgroundColor = UIColor(red: 230.0/255.0, green: 110.0/255.0, blue: 102.0/255.0, alpha: 1.0)
    }
    else if section == 1
    {
        headerCell.reminder.text = "It is not Time"
        headerCell.count.text = String(arrayTwo.count)
        headerCell.contentView.backgroundColor = UIColor(red: 113.0/255.0, green: 220.0/255.0, blue: 110.0/255.0, alpha: 1.0)
    }

    return headerCell.contentView
}

Within editActionsForRowAt, I've implemented the functionality to allow the user to swipe left to delete a specific row. However, I'd like to gain access to headerCell.count.text and update the number of rows in that section header without having to call tableView.reloadData to reload the whole table view.

I've found similar questions and answers here:

  1. Changing UITableView's section header/footer title without reloading the whole table view
  2. Dynamically change the section header text on a static cell
  3. Update the header in tableView swift

However, the suggestions/solutions did not help me fix my issue.

How can I gain access to my custom section header cell label within editActionsForRowAt to update the count?

Thanks.

Upvotes: 2

Views: 5042

Answers (2)

Ashwini Chougale
Ashwini Chougale

Reputation: 1093

try reloadSections method :

In Swift

let sectionToReload = 1
let indexSet: IndexSet = [sectionToReload]

self.tableView.reloadSections(indexSet, with: .automatic)

In Objective c

- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation

Upvotes: 4

Malik
Malik

Reputation: 3802

There is a hackish way. Not sure if it will work but worth giving it a try. Just use

tableView.beginUpdates()
tableView.endUpdates()

You don't need to perform any actual updates. The idea is that when the tableView gets a call for begin and end updates, it should, theoretically speaking, refresh any changes made to the table. I'm hoping it would update the section headers in your case. Let me know if it works.

Upvotes: 1

Related Questions