Using .backgroundPreferenceValue To Create a Background Based On a PreferenceKey In iOS 16
Daily Coding Tip 150
Celebrating 150 Daily Coding Tips 🎉 this one is free for everyone 😀
I can freely admit I’ve not really found a use for preference keys.
Nevertheless, there’s a new modifier called .backgroundPreferenceValue
that reacts to changes in a type conforming to the PreferenceKey
protocol. When that type is changed, the value is passed into the closure provided to the modifier. the closure is used to construct a view that is then used as the background for the view.
It is necessary to first create the BGPreferenceKey
type, and it must have a default value and a way of dealing with versions of the value elsewhere in the view hierarchy.
In Apple’s documentation, the purpose of this is to combine “a sequence of values by modifying the previously-accumulated value with the result of a closure that provides the next value.”
I have a ColorPicker
that sets the BGPreferenceKey
’s associated value to the colour that it selects.
The background is a Text
that sets its foreground colour according to the change in the preference key.
This is a somewhat artificial use case, as the colour could easily be passed directly, but the preference key can be used at different places in the view hierarchy.