So I'm trying to get the UITableView section headers to change in background and text color when switching from one segment to another on a segmented control. To so so I need to reload the tableView data but I only want to reload the section headers. When using

tableView.reloadData()

It works but it also resets the rest of the data in the tableView which I'm not trying to do.

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        let stringForThemeHeader = "Theme Settings"
        let stringForToggleHeader = "Password Settings"
        if section == 0 {
            return stringForThemeHeader
        } else {
            return stringForToggleHeader
        }
    }

That's the code for setting up the titles.

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        let header = view as! UITableViewHeaderFooterView
        if darkModeSegmentedControlSwitcher.selectedSegmentIndex == 1 || darkModeSegmentedControlSwitcher.selectedSegmentIndex == 2 {
            view.tintColor = UIColor.red
            header.textLabel?.textColor = UIColor.white
        } else {
            view.tintColor = UIColor.init(red: 247.0/255.0, green: 247.0/255.0, blue: 247.0/255.0, alpha: 1.0)
            header.textLabel?.textColor = UIColor.black
        }

    }

and that's the code to change the text and background. After a segment is selected it doesn't change unless the data of the entire tableView is reloaded using

tableView.reloadData()

So I just need to know how to reload only the section headers and my problem will be solved.

1 Answers

0
Michael Krutoyarskiy On

You can just manually iterate the section headers.

for section in 0..<tableView.numberOfSections {
    guard let header = tableView.headerView(forSection: section) else {
        continue
    }
    // do something with the header
}

In case you have a lot of the sections you can iterate only visible headers. Just use tableView.visibleCells to collect the visible sections indexes.