I have a SwiftUI
native Watch app I Am working on. I have a Combine
based class that allows me to store `\userDefaults, one of which is a simple toggle.
import SwiftUI
import Foundation
import Combine
class MeetingSetup: BindableObject {
let willChange = PassthroughSubject<Void, Never>()
var twitterEnabled: Bool = false {
didSet {
willChange.send()
}
}
init() {
let prefs:UserDefaults = UserDefaults(suiteName: "group.com.appname")!
twitterEnabled = prefs.bool(forKey: "keyTwitterEnabledBool")
}
}
In the SwiftUI
I am getting the error messages that Bool
is not convertible to Binding<Bool>
import SwiftUI
import Combine
struct SetupView : View {
@ObjectBinding var meetingSetup: MeetingSetup = delegate.meetingSetup
var body: some View {
HStack{
Toggle(isOn: self.meetingSetup.twitterEnabled){ // <== 'Bool' in not convertible to 'Binding<Bool>'
Text("Twitter")
}
}
}
I don't understand why this is getting the message since the code is @ObjectBinding
, should it not be Binding<Bool>
by definition? If not how do I address this correctly??
What's @Binding in SwiftUI? A binding is essentially a connection between a value, like a Bool, and an object or UI element that displays and changes it, like a slider or text field. The connection is two-way, so the UI element can change the value, and the value can change the UI element.
Binding is a property wrapper that creates a connection between stored data, and a view that displays and changes that data. It is a two-way connection to a source of truth. It is used to both read the latest value, as well as to set a new value.
You missed the dollar sign:
Toggle(isOn: self.$meetingSetup.twitterEnabled) { ... }
I also noticed that you are using didSet
in your @BindableObject
, but you should really be using willSet
.
And finally, maybe you pasted incompletely, but you are missing a closing bracket in your view.
If you don't know what the dollar sign is for, check the WWDC2019 video Data Flow in SwiftUI.
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