Created
July 24, 2020 18:47
-
-
Save IanKeen/1bb257ab79058318581047f5c9ae7be3 to your computer and use it in GitHub Desktop.
SwiftUI: Show a sheet based on an optionals unwrapped value
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
@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() | |
} | |
} | |
} | |
} | |
} |
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
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!) | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(Got here from a link you pasted in Slack.)
Clever!