To bind objects your variable needs to conform to one of the new wrappers @State
, @Binding
, @ObservableObject
, etc.
Because your RegistrationViewModel
doesn't conform to View
the only way to do it is to have your RegistrationViewModel
conform to ObservableObject
.
class RegistrationViewModel: ObservableObject {
@Published var firstname: String?
}
Once that is done you can call it View
using
@ObservedObject var resgistrationVM: RegistrationViewModel = RegistrationViewModel()
or as an @EnvironmentObject
https://developer.apple.com/tutorials/swiftui/handling-user-input
Also, SwiftUI does not work well with optionals but an extension
can handle that very easily.
SwiftUI Optional TextField
extension Optional where Wrapped == String {
var _bound: String? {
get {
return self
}
set {
self = newValue
}
}
public var bound: String {
get {
return _bound ?? ""
}
set {
_bound = newValue.isEmpty ? nil : newValue
}
}
}