Last active
February 25, 2021 07:15
-
-
Save aaronlab/21bdcc534188b967762bec69abab0ccc to your computer and use it in GitHub Desktop.
SwiftUI: Chooseable ViewModifier to use fullScreenCover and sheet modal at the same time.
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
// MARK: - Modifier | |
/// Choosable Sheet for FullScreen or Sheet Modal | |
struct ChooseableSheet<Destination>: ViewModifier where Destination: View { | |
// Select it's fullscreen sheet or modal sheet | |
@Binding var isFullScreen: Bool | |
@Binding var isPresented: Bool | |
private let fullScreenContent: () -> Destination? | |
private let modalContent: () -> Destination? | |
init( | |
isFullScreen: Binding<Bool>, | |
isPresented: Binding<Bool>, | |
@ViewBuilder fullScreenContent: @escaping () -> Destination? = { nil }, | |
@ViewBuilder modalContent: @escaping () -> Destination? = { nil } | |
) { | |
self._isFullScreen = isFullScreen | |
self._isPresented = isPresented | |
self.fullScreenContent = fullScreenContent | |
self.modalContent = modalContent | |
} | |
func body(content: Content) -> some View { | |
if isFullScreen { | |
return AnyView( | |
content | |
.fullScreenCover(isPresented: $isPresented) { | |
fullScreenContent() | |
} | |
) | |
} else { | |
return AnyView( | |
content | |
.sheet(isPresented: $isPresented) { | |
modalContent() | |
} | |
) | |
} | |
} | |
} | |
// MAKR: - Useage | |
struct MyView: View { | |
@State private var isFullScreen: Bool = false | |
@State private var isPresented: Bool = false | |
var body: some View { | |
ZStack { | |
Button(action: { | |
isFullScreen.toggle() | |
isPresented.toggle() | |
}) { | |
Text("Toggle FullScreen / Modal") | |
} | |
} | |
.modifier( | |
ChooseableSheet( | |
isFullScreen: $isFullScreen, | |
isPresented: $isPresented, | |
fullScreenContent: { getFullScreenContent() }, | |
modalContent: { getSheetContent() } | |
) | |
) | |
} | |
@ViewBuilder | |
private func getFullScreenContent() -> AnyView { | |
AnyView( | |
Text("Full Screen") | |
) | |
} | |
@ViewBuilder | |
private func getSheetContent() -> AnyView { | |
AnyView( | |
VStack { | |
Text("Sheet Model") | |
} | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment