Created
June 15, 2025 20:26
-
-
Save lukaskollmer/5ca7eb3887dde3f3faba2cab29e8bc36 to your computer and use it in GitHub Desktop.
View.sheet(item:id:onDismiss:content)
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
// | |
// This source file is part of the Stanford Spezi open-source project | |
// | |
// SPDX-FileCopyrightText: 2025 Stanford University and the project authors (see CONTRIBUTORS.md) | |
// | |
// SPDX-License-Identifier: MIT | |
// | |
import Foundation | |
import SwiftUI | |
private struct IdentifiableAdaptor<Value, ID: Hashable>: Identifiable { | |
let value: Value | |
private let _id: (Value) -> ID | |
var id: ID { _id(value) } | |
init(value: Value, id: @escaping (Value) -> ID) { | |
self.value = value | |
self._id = id | |
} | |
} | |
extension View { | |
public func sheet<Item, ID: Hashable>( | |
item: Binding<Item?>, | |
id: @escaping (Item) -> ID, | |
onDismiss: (@MainActor () -> Void)? = nil, | |
@ViewBuilder content: @MainActor @escaping (Item) -> some View | |
) -> some View { | |
let binding = Binding<IdentifiableAdaptor<Item, ID>?> { | |
if let item = item.wrappedValue { | |
IdentifiableAdaptor(value: item, id: id) | |
} else { | |
nil | |
} | |
} set: { newValue in | |
if let newValue { | |
item.wrappedValue = newValue.value | |
} else { | |
item.wrappedValue = nil | |
} | |
} | |
return self.sheet(item: binding, onDismiss: onDismiss) { item in | |
content(item.value) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment