When employing sheet(item:onDismiss:content:), are there specific considerations that we need to take into account? I have a class, Presenter, that centrally manages all presentations, and I utilize the DynamicProperty of CustomProperty to update UserDefaults (for simplicity, its code is omitted here). The provided code demonstrates the correct functionality of sheet(isPresented:onDismiss:content:). However, when incorporating sheet(item:) within the given structure, the slider fails to move, although the value is updated, and the reset button does not function.
import SwiftUI
@propertyWrapper
private struct CustomProperty: DynamicProperty {
@State private var value : CGFloat
init(value: CGFloat) {
self.value = value
}
var wrappedValue: CGFloat {
get { value }
nonmutating set { value = newValue }
}
var projectedValue: Binding<CGFloat> {
.init(get: { wrappedValue }, set: { wrappedValue = $0 })
}
}
private struct SheetView: View {
@Binding var fontSize: CGFloat
var body: some View {
VStack {
Slider(value: $fontSize, in: 20...40)
Button("reset") {
fontSize = 30
}
}
}
}
@Observable
private class Presenter {
struct Sheet: Identifiable {
let id = UUID()
let view: AnyView
}
var currentSheet: Sheet?
static let shared = Presenter()
}
struct SwiftUIView: View {
@State var show: Bool = false
@Bindable private var presenter = Presenter.shared
@CustomProperty(value: 30) private var fontSize
var body: some View {
VStack {
Text("fontSize: \(Int(fontSize))").bold()
Button("show (isPresented:)") {
show.toggle()
}
Button("show (item:)") {
let sheet = Presenter.Sheet(view: AnyView(SheetView(fontSize: $fontSize)))
Presenter.shared.currentSheet = sheet
}
}
.sheet(isPresented: $show) {
AnyView(SheetView(fontSize: $fontSize)
.presentationDetents([.height(200)]))
}
.sheet(item: $presenter.currentSheet) { sheet in
sheet.view
.presentationDetents([.height(200)])
}
}
}
#Preview {
SwiftUIView()
}