3

I'm trying to create different themes for an app I'm creating in Xcode, with the latest version of Swift. So basically how I'm thinking to get it to work is

  1. after the user presses a theme in a special "themes" page, there will be a variable(let's just call the variable 'theme') changed
  2. according to the variable's value, the other pages will change their colors, styles, etc.

Why I'm asking this question is because I'm not sure how the other view controllers can access the variable 'theme' and its current value. Each view controller class is located in separate files.

I read some other answers to similar questions, but they don't seem to work. Any help would be appreciated

2 Answers 2

4

Share it with

option 1 Singleton

class Service {
  static let shared = Service()
  var theme:Theme = .black
}

option 2 global var

var theme:Theme = .black

and

enum Theme { case black,white }

regarding the refresh every vc should be configued to use this variable in worst case inside viewDidAppear

Sign up to request clarification or add additional context in comments.

1 Comment

The best option would be UserDefaults as above options will lose your stored data if your app is killed or crashes.
2

There are lot of solutions:

  • a singleton class, then you call the shared instance inside all your view controllers
  • if you have factories for your view controllers, you can pass it using dependency injection (this is somehow advanced concept)
  • store the theme in the AppDelegate. AppDelegate is a singleton and you can get a reference of it from everywhere
  • store the theme as a dictionary in NSUserDefaults, read it inside your view controllers
  • ...

Other thing is how you refresh your current views/view controllers already pushed on the navigation controller. Inside viewDidAppear is a first approach, but in some cases you need to send a notification using Notification Center to all live instances of your view controllers/views to refresh. Here you have a nice example using a protocol for that purpose.

https://academy.realm.io/posts/architecting-a-robust-color-system-swift-tryswift-2017-ragone/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.