Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ryanlintott/a7884a04eb3ea06c2210091fc2571a5c to your computer and use it in GitHub Desktop.
Save ryanlintott/a7884a04eb3ea06c2210091fc2571a5c to your computer and use it in GitHub Desktop.
Sets the disfavored locations for a widget if the option is available (iOS 17 and up). Otherwise returns the same configuration.
//
// 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
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment