Search code examples
iosswiftuitableviewbackground-coloruitableviewsectionheader

Updating the background colour of UITableView section header


In my App, I let users change the main theme colour and then UI elements are updated accordingly. I have a Navigation Controller, which is embedded into a Tab Bar Controller.

The App has two tabs, main screen (which has the Navigation controller) and the settings tab (single UIViewController). When users change the theme colour from the settings page, and go back to main screen (i.e. switch tabs), the background colour of the section headers in UITableView are not updated.

I use tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) to set the background colour of section headers, but, apparently, this method is not called when the user switches between tabs.

I have to use the Navigation Controller (i.e. navigate to another view and come back to main screen) to update the colours of the UITableView section header.

How can I get the colours updated when the user returns back from the settings tab to the main screen?

I use Swift 4.1

Thanks


Solution

  • The proper solution for your task is to use a notification. When the user updates a setting, use NotificationCenter to post a notification such as "color scheme changed".

    Then any class that needs to perform an action when this notification is posted can register to receive this specific notification.

    You can have this view controller listen for the notification and reload the table view as needed. Any other views, controls, or controllers that also need to update themselves based on the notification can register as well and update themselves as needed.

    This is a much better solution than relying on other events such as a view becoming visible again. It also eliminates needlessly reloading a table every time the view controller is viewed even if the user didn't change any setting.