udi
udi

Reputation: 317

Change text of a label in the tableview section header

I have an expandable tableview with custom headers. I need to change a text of a label in the header when the table is expanding. I used below code for this.

func toggleSection(header: SuperHeaderDelegate, section: Int) {
        sections[section].expanded = !sections[section].expanded

        tableView.beginUpdates()
        tableView.reloadSections([section], with: .automatic)
        tableView.endUpdates()

        if let head = header as? SavingAccountHeaderView {
            head.accNoLabel.text = "HIIIIIII"
        }
        else { print("NOPE") }

    }

When I use this code it changes the accNoLabel text to new text and change it back to the old text again.

I have tried the tableView.reloadData() instead of the tableView.reloadSections(), then the code worked fine. The accNoLabel didn't change back to its old text. But I really need to use the tableView.reloadSections() to use the animation. So could anyone tell me what I'm doing wrong?

Upvotes: 0

Views: 174

Answers (1)

Kunal Shah
Kunal Shah

Reputation: 1121

Couple of things you should check:

  1. Is your 'expanded' toggle happening at the right place (and time)?
  2. reloadSections() is an asynchronous function. So you can't expect your text to be updated 'after' the updates have been completed.

I would suggest toggling your label's text inside the viewForHeader function, because at this point you can be sure that the reloadSections() method is being called and the section's state has already been updated.

Upvotes: 1

Related Questions