Last active
May 5, 2025 19:59
-
-
Save ryanlintott/a7884a04eb3ea06c2210091fc2571a5c to your computer and use it in GitHub Desktop.
Extensions for WidgetConfiguration that make it easier to add disfavoredLocations and promptsForUserConfiguration while supporting older versions of iOS.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // WidgetConfiguration+extensions.swift | |
| // | |
| // | |
| // Created by Ryan Lintott on 2023-09-11. | |
| // | |
| import SwiftUI | |
| import WidgetKit | |
| /// An enum with options that match `WidgetLocation` | |
| public enum WidgetLocationIfAvailable: Equatable, Hashable, Sendable { | |
| /// The Home Screen, Today View, Mac desktop, or similar location. | |
| case homeScreen | |
| /// The Lock Screen location. | |
| case lockScreen | |
| /// The location that indicates a widget from another device that appears on the Mac. | |
| case iPhoneWidgetsOnMac | |
| /// The StandBy location. | |
| case standBy | |
| /// The equivalent `WidgetLocation` | |
| @available(iOS 17, *) | |
| public var location: WidgetLocation { | |
| switch self { | |
| case .homeScreen: .homeScreen | |
| case .lockScreen: .lockScreen | |
| case .iPhoneWidgetsOnMac: .iPhoneWidgetsOnMac | |
| case .standBy: .standBy | |
| } | |
| } | |
| } | |
| extension WidgetConfiguration { | |
| /// Sets the disfavored locations for a widget if the option is available (iOS 17 and up). Otherwise returns the same configuration. | |
| /// - Parameters: | |
| /// - locations: An array of disfavored locations for a widget. | |
| /// - families: The families you want to mark as disfavored in the given locations. | |
| public func disfavoredLocationsIfAvailable(_ locations: [WidgetLocationIfAvailable], for families: [WidgetFamily]) -> some WidgetConfiguration { | |
| if #available(iOS 17, *) { | |
| return self.disfavoredLocations(locations.map(\.location), for: families) | |
| } else { | |
| return self | |
| } | |
| } | |
| /// Specifies that a widget’s configuration UI should be automatically presented after the widget is added if the option is available (iOS 18 adn up). Otherwise returns the same configuration. | |
| public func promptsForUserConfigurationIfAvailable() -> some WidgetConfiguration { | |
| if #available(iOS 18, *) { | |
| return self.promptsForUserConfiguration() | |
| } else { | |
| return self | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment