To set a default or nil value for @Binding in the initializer of a SwiftUI View, you can use a property wrapper called @State. Here is an example:
struct MyView: View {
@Binding var myBinding: Bool
init(myBinding: Binding<Bool> = .constant(false)) {
_myBinding = State<Bool>(initialValue: myBinding.wrappedValue)
}
var body: some View {
// ...
}
}
In this example, we use the @State property wrapper to store the initial value of our binding in the _myBinding property, which is then used as the source of our @Binding property. If no value is provided for myBinding when the view is initialized, we default to a constant value of false.
Asked: 2023-07-04 22:47:35 +0000
Seen: 15 times
Last updated: Jul 04 '23