ios – Is it to mechanically apply themes to SwiftUI controls as with Subclasses+Protocols+Look in UIKit?


After working with UIKit for fairly some time I’m now making my first steps in SwiftUI. In UIKit it’s fairly straightforward apply completely different themes to an app (e.g. as described right here):

  1. Create completely different subclasses for controls which ought to have completely different types. E.g. class HeadlineLabel: UILabel {} and class BodyLabel: UILabel {}
  2. Outline a Theme protocol which controls the completely different styling choices like completely different fonts + textual content sizes for the completely different label sorts.
  3. Create a ThemeManager which applies the types of the present Theme to the controls utilizing the looks proxy. E.g. HeadlineLabel.look().textColor = theme.headlineColor

The massive benefit of this method is, that in the remainder of the code one has not take into consideration theming in any respect. All one has to do, is to make use of the right management subclasses (HeadlineLabel, and so forth.) inside the XIB or Storyboard information.

Is that this additionally doable when working with SwiftUI?


In fact it’s no downside to create and use a theme protocol when working with SwiftUI. Nonetheless, since a SwiftUI view is a struct, one can not create customized sub lessons like struct HeadlineText: Textual content or struct BodyText: Textual content, just because structs should not have inheritance…

So the one answer I discovered, is to use the theming choices to all controls manuall:

...
Textual content("Headline 1")
    .foregroundColor(ThemeManager.currentTheme.headlineColor)
Textual content("Physique 1")
    .foregroundColor(ThemeManager.currentTheme.bodyColor)

Textual content("Headline 2")
    .foregroundColor(ThemeManager.currentTheme.headlineColor)
Textual content("Physique 2")
    .foregroundColor(ThemeManager.currentTheme.bodyColor)

// Not doable
HeadlineText("Headline 3)
BodyText("Physique 3")

Is that this right? Or is feasible to use types to SwiftUI controls of a standard kind mechanically?

Leave a Reply