I have a binding in a swiftUI view. Something along the lines of :
struct MyCoolView: View { @ObservedObject var viewModel: ViewModel var body: some View { Text("Here is a cool Text!").sheet(isPresented: $viewModel.MyProperty) { SomeModalView()} } }
I want the isPresented to use the opposite boolean value of what is stored in the property.
Swift wont let me just do something like
.sheet(isPresented: !$viewModel.MyProperty)
(It gives me an error about cannot convert Binding <Bool>
to Bool
)
Any thoughts on how to deal with this?
What about creating a custom prefix operator?
prefix func ! (value: Binding<Bool>) -> Binding<Bool> { Binding<Bool>( get: { !value.wrappedValue }, set: { value.wrappedValue = !$0 } ) }
Then you could run your code without any modification:
.sheet(isPresented: !$viewModel.MyProperty)
If you don't like operators you could create an extension on Binding type:
extension Binding where Value == Bool { var not: Binding<Value> { Binding<Value>( get: { !self.wrappedValue }, set: { self.wrappedValue = !$0 } ) } }
and later do something like:
.sheet(isPresented: $viewModel.MyProperty.not)
or even experiment with a global not function:
func not(_ value: Binding<Bool>) -> Binding<Bool> { Binding<Bool>( get: { !value.wrappedValue }, set: { value.wrappedValue = !$0 } ) }
and use it like that:
.sheet(isPresented: not($viewModel.MyProperty))
You can build a binding by yourself:
Text("Here is a cool Text!").sheet(isPresented: Binding<Bool>(get: {return !self.viewModel.MyProperty}, set: { p in self.viewModel.MyProperty = p}) { SomeModalView()} }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With