CoolUserName
CoolUserName

Reputation: 137

Access Variable From Another Class Swift

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

Upvotes: 3

Views: 2356

Answers (2)

Christian Slanzi
Christian Slanzi

Reputation: 25

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/

Upvotes: 2

Shehata Gamal
Shehata Gamal

Reputation: 100523

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

Upvotes: 4

Related Questions