简体   繁体   中英

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 (ie 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 (ie 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM