使用 UITraitCollection 进行现代 iOS 主题设置

  • Introduction: Apple introduced a new way to handle theme changes in iOS 17. Before, it was difficult. With UITraitAppearance, things are better. This post shows how to add theming in a real app and includes sample code.

    • Prerequisites: App must target iOS 17 or later and use a scene delegate.
  • Understanding Trait Collections: Trait collections have been around since iOS 8. They represent the environment for UI elements. UITraitCollection is immutable, but UIMutableTraits allows us to manipulate traits. We conform our trait to UITraitDefinition and add getters and settings in a UIMutableTraits extension.
  • Defining Your Theme: Use UIColor's dynamic initializer to define colors. Create a trait definition and extend UITraitCollection and UIMutableTraits to add the theme.
  • Using Your Theme: Apply theme values to UI elements dynamically. Use trait overrides to change the theme. On application startup, set the theme in the scene(_:willConnectTo:options:) method. Here's a full scene delegate implementation and a corresponding theme store. To change the theme dynamically, update the theme store and the trait overrides.
  • Conclusion: Only scratched the surface on theming possibilities. Recommended resources include articles and WWDC videos.
  • Or, Just Download the Sample Code: Check out iOSTraitCollectionThemingExample on GitHub for an example app.
阅读 7
0 条评论