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, butUIMutableTraits
allows us to manipulate traits. We conform our trait toUITraitDefinition
and add getters and settings in aUIMutableTraits
extension. - Defining Your Theme: Use
UIColor
's dynamic initializer to define colors. Create a trait definition and extendUITraitCollection
andUIMutableTraits
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.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。