Last active
October 26, 2024 02:45
-
-
Save huntercmeyer/3581049c1a9ca59bdb3d197760a23cd2 to your computer and use it in GitHub Desktop.
A SwiftUI view modifier to present a sheet using a given item as a data source, where the sheet's content is passed a Binding to that item.
This file contains 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
import SwiftUI | |
struct SheetBinding<Item: Identifiable, SheetContent: View>: ViewModifier { | |
@Binding var item: Item? | |
let onDismiss: (() -> Void)? | |
@ViewBuilder let sheetContent: (Binding<Item>) -> SheetContent | |
@ViewBuilder func body(content: Content) -> some View { | |
content | |
.sheet(item: self.$item, onDismiss: self.onDismiss) { newItem in | |
self.sheetContent(Binding { | |
newItem | |
} set: { | |
self.item = $0 | |
}) // sheetContent | |
} // .sheet | |
} // body | |
} // SheetBinding | |
extension View { | |
/// Presents a sheet using the given item as a data source for the sheet’s content. | |
/// | |
/// This differs from other sheet implementations with a custom `Binding<Item?>` in that the content closure accepts a `Binding<Item>`, as opposed to an `Item`. This allows you to inject your `Binding<Item>` into your sheet's content. | |
@ViewBuilder func sheet<Item, Content>(item: Binding<Item?>, onDimiss: (() -> Void)? = nil, @ViewBuilder content: @escaping (Binding<Item>) -> Content) -> some View where Item: Identifiable, Content: View { | |
self.modifier(SheetBinding(item: item, onDismiss: onDimiss, sheetContent: content)) | |
} // View.sheet(item:onDimiss:content:) | |
} // extension View | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment