Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Created July 24, 2020 18:47
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IanKeen/1bb257ab79058318581047f5c9ae7be3 to your computer and use it in GitHub Desktop.
Save IanKeen/1bb257ab79058318581047f5c9ae7be3 to your computer and use it in GitHub Desktop.
SwiftUI: Show a sheet based on an optionals unwrapped value
@main
struct MyApp: App {
enum Sheet { case first, second }
@State var sheet: Sheet? = nil
var body: some Scene {
WindowGroup {
VStack {
Button("First") { sheet = .first }
Button("Second") { sheet = .second }
}
.sheet(using: $sheet) { sheet in
switch sheet {
case .first:
FirstView()
case .second:
SecondView()
}
}
}
}
}
extension View {
public func sheet<Content: View, Value>(
using value: Binding<Value?>,
@ViewBuilder content: @escaping (Value) -> Content
) -> some View {
let binding = Binding<Bool>(
get: { value.wrappedValue != nil },
set: { _ in value.wrappedValue = nil }
)
return sheet(isPresented: binding) {
content(value.wrappedValue!)
}
}
}
@loganmoseley
Copy link

(Got here from a link you pasted in Slack.)

Clever!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment