Reputation: 127
I am trying to change the header of a tableview depending on what button a user selects. But when I do this, the header value says nil. How do I fix this so that it displays the proper title?
Here is the code I have so far.
@IBOutlet weak var tableView: UITableView!
var sectionHeader = “”
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == “segue” { sectionHeader = “Title 1” }}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return “\(sectionHeader)” }
}
How would I go about changing this so that it displays the proper header based off of what button is pressed?
Upvotes: 0
Views: 105
Reputation: 4552
titleForHeaderInSection
is not called dynamically, but only when it needs to be called (once to show the data initially, and then when the header reappears on the screen during scrolling).
If you just want to refresh everything, call tableView.reloadData()
If you need to preserve the scrolling and don't want the reload animation, you can either trick the tableView to refresh after changing the title by calling this block:
tableView.beginUpdates()
tableView.endUpdates()
Or you can also access the title directly, which may stop working sometime:
tableView.headerView(forSection: indexPath.section)?.textLabel?.text = "Some text"
You might need to put the line above in the block above it.
Upvotes: 1