Widescreen app themes in Swift on iOS

I have a solution, but for me it seems like a very hacky and not very elegant solution. But I searched, searched and could not find anything else. Maybe someone can suggest a better solution?

So, the problem is, I want to have one file where I define all the colors and fonts and such an application. I created a style structure with a bunch of static vars, like this:

struct Style{ static var colorA = UIColor.redColor() static var colorB = UIColor.blackColor() static var titleText = colorA static var mainText = colorA static var backColor = colorB static var callBackColor = backColor } 

I need to use start var because I want to be able to refer to previously declared variables in the definitions of new variables and that is the only way to make it work.

In general, the above works well. For example, in my code, I can always refer to a color or other text as Style.titleText . So it looks like a good solution.

However, then I decided to add topics. To do this, I added a static method called theme1 , which overwrites some of the static vars on top and adds a theme selector. Simple enough:

 struct Style{ static var colorA = UIColor.redColor() static var colorB = UIColor.blackColor() static var titleText = colorA static var mainText = colorA static var backColor = colorB static var callBackColor = backColor static func themeSelector(){ // some logic loading defaults and running appropriate theme function bellow } static func theme1(){ backColor = UIColor.greenColor() callBackColor = UIColor.greenColor() } } 

But then I ran into a problem, how to start themeSelector ? I tried to override the initialization method and convert my structure to a class, but the initializer function did not work on time, so some variables that relied on style parameters in their description statements did not load with updated theme settings, but rather by default.

I also tried putting the call into the didFinishLaunchingWithOptions AppDelegate method, but the same result as above.

In the end, I did something really idiotic by declaring a variable in my ViewController class as follows:

 var loadThem: Bool = { Style.themeSelector() return true }() 

It works, but ... really, this is the best way. Is there a better way to make themes? Is there a better way to call a function when loading a class or structure (overriding the loading method is no longer an option with Swift 1.2). So is there a better way?

+6
source share

Source: https://habr.com/ru/post/986615/


All Articles