I'm trying to ascertain the widgetRenderingMode
and other context info from a widget timeline generator, but I see a weird build error with this code:
func getTimeline(for configuration: AccessoryOptionsIntent, in context: Context, completion: @escaping (Timeline<AccessoryEntry>) -> Void) {
if #available(iOSApplicationExtension 16.0, *) {
if let mode: [WidgetRenderingMode] = context.environmentVariants.widgetRenderingMode {
}
}
Cannot assign to property: 'environmentVariants' is a 'let' constant
How can I determine the rendering mode from the timeline?
See also: https://twitter.com/_DavidSmith/status/1578045086507696129
CodePudding user response:
You probably meant to read the current rendering mode, which can be read just like any other EnvironmentValues
in SwiftUI.
@Environment(\.widgetRenderingMode) var widgetRenderingMode
I'm not sure why your code doesn't compile though. In theory, accessing widgetRenderingMode
should compile because TimelineProviderContext.EnvironmentVariants
is marked with @dynamicMemberLookup
. Your access would be turned into a key path and passed into this subscript:
subscript<T>(dynamicMember keyPath: WritableKeyPath<EnvironmentValues, T>) -> [T]? { get }
which is a read-only subscript and does not involve setting environmentVariant
.
TimelineProviderContext.EnvironmentVariants
does have another subscript that does work for me:
subscript<T>(keyPath: WritableKeyPath<EnvironmentValues, T>) -> [T]? { get }
You can use it like this:
if let mode = context.environmentVariants[\.widgetRenderingMode] {
}