sheet(unwrapping:) shows a blank view #151
-
DescriptionWhen using Given the following code from State-driven navigation:
When I tap the "Show sheet" button, I'd expect to see a sheet with the TextField containing "Hello!". Instead, I see a blank sheet. This seems to be broken on Checklist
Expected behaviorI expected to see the TextField in a sheet with the text "Hello!". Actual behaviorI saw a blank sheet. Steps to reproduceWith the code above, this is what I see when I tap the button: Simulator.Screen.Recording.-.iPhone.15.-.2024-05-10.at.14.21.46.mp4Full project attached (though it's just the above code inside an otherwise empty project). SwiftUI Navigation version information1.3.0 Destination operating systemiOS 17.4 Xcode version information15.3 (15E204a) Swift Compiler version informationswift-driver version: 1.90.11.1 Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4)
Target: arm64-apple-macosx14.0 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Unfortunately this seems to be a SwiftUI bug with class FeatureModel: ObservableObject {
@Published var presentedValue: String?
}
struct FeatureView: View {
@ObservedObject var model = FeatureModel()
var body: some View {
Button("Show sheet") {
self.model.presentedValue = "Hello!"
}
.sheet(unwrapping: self.$model.presentedValue) { $value in
TextField("Value", text: $value)
}
}
} It also works fine with the newer @Observable
class FeatureModel {
var presentedValue: String?
}
struct FeatureView: View {
@Bindable var model = FeatureModel()
var body: some View {
Button("Show sheet") {
self.model.presentedValue = "Hello!"
}
.sheet(unwrapping: self.$model.presentedValue) { $value in
TextField("Value", text: $value)
}
}
} And it even works with struct FeatureView: View {
@State var presentedValue: String?
var body: some View {
Button("Show sheet") {
self.presentedValue = "Hello!"
}
.sheet(
unwrapping: Binding(
get: { presentedValue },
set: { presentedValue = $0 }
)
) { $value in
Text("Hi")
TextField("Value", text: $value)
}
}
} While we'd love to work around the bug in the library, I'm not sure if it's possible to detect if a binding is being derived from Note that ad hoc bindings can be buggy when it comes to SwiftUI animations and transactions, which is why this library prefers derived bindings. Sadly it seems that you should generally prefer to avoid Since this is a bug with SwiftUI and not the library, I'm going to convert to a discussion, but good find! |
Beta Was this translation helpful? Give feedback.
Unfortunately this seems to be a SwiftUI bug with
@State
and derived bindings. If you change to use an observable object it works fine:It also works fine with the newer
@Observable
macro and@Bindable
: