Skip to content

Instantly share code, notes, and snippets.

@sindresorhus
Created October 10, 2019 17:23
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sindresorhus/442e81498c77da6c4ade9de06396b2eb to your computer and use it in GitHub Desktop.
Save sindresorhus/442e81498c77da6c4ade9de06396b2eb to your computer and use it in GitHub Desktop.
SwiftUI modifier to show a view only a given amount of app runs.
// Depends on https://github.com/sindresorhus/Defaults
@available(macOS 10.15, *)
private struct ShowForAppRuns: ViewModifier {
private static var runCounts = [String: Int]()
private let count: Int
private let startShowingFromAppRun: Int
private let runCount: Int
init(count: Int, id: String, startShowingFromAppRun: Int = 1) {
assert(startShowingFromAppRun >= 1)
self.count = count
self.startShowingFromAppRun = startShowingFromAppRun
self.runCount = {
guard let count = Self.runCounts[id] else {
let key = Defaults.Key<Int>("SS_ShowForAppRuns_\(id)", default: 0)
Defaults[key] += 1
let count = Defaults[key]
Self.runCounts[id] = count
return count
}
return count
}()
}
func body(content: Content) -> some View {
if
runCount >= startShowingFromAppRun,
runCount < (count + startShowingFromAppRun)
{
return AnyView(content)
} else {
return AnyView(EmptyView())
}
}
}
@available(macOS 10.15, *)
extension View {
// TODO: Improve method and parameter naming.
/**
Show the view only for the given amount of app runs.
- Parameter count: Show the view this many app runs.
- Parameter id: Identifier for the view. Should be unique in the app. Prefer camel case notation.
- Parameter startShowingFromAppRun: Start showing the view at this app run count.
Tip: Specify `0` as `count` to see how it will look like as hidden.
```
// This shows the text on the second time the app is run and shows it for two app runs.
Text("🦄").showForAppRun(2, id: "unicornText", startShowingFromAppRun: 2)
```
*/
func showForAppRuns(_ count: Int, id: String, startShowingFromAppRun: Int = 1) -> some View {
modifier(ShowForAppRuns(count: count, id: id, startShowingFromAppRun: startShowingFromAppRun))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment