0

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

fnisi
  • 1,181
  • 1
  • 14
  • 24
  • 1
    It sounds as if you might be setting the `backgroundColor` of the section header view. That is wrong. Give the section header a `backgroundView` and set _that_ view's `backgroundColor`. – matt Oct 02 '18 at 22:40

1 Answers1

2

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Thanks! I found the problem! I was saving the selected colour into userdefaults, but my code was updating the relevant value in `viewDidLoad()`, which runs only once. Once I moved the code snippet updating the selected colour into `viewWillAppear()`, all worked fine. I like the `NotificationCentre` approach, which sounds like a more Swifty way of doing things. Thanks – fnisi Oct 02 '18 at 23:36