Learn how to correctly move FosucState from observable class to view’s subview? I’ve tried however it’s not working correctly
I’ve a
1. enum to symbolize enter fields of login view
enum LoginInputFields {
case e-mail
case password
}
2. Reusable TextField view
struct AuthTF<FieldType: Hashable>: View {
@State var isFocusd: Bool = false
@Binding var textual content: String
var focusedField: FocusState<FieldType?>.Binding
let placeholder: String
let leadingIconName: String
let keyboardType: UIKeyboardType
let submitLabel: SubmitLabel
let fieldType: FieldType
let onSubmit: VoidCallback
var physique: some View {
VStack(spacing: 0) {
// 1. Content material
HStack {
// 1. Icon
Picture(systemName: leadingIconName)
.foregroundColor(isFocusd ? AppColor.cWhite : AppColor.cD3D3D3)
// 2. TF
TextField(placeholder,
textual content: $textual content,
onEditingChanged: { isEditing in
isFocusd = isEditing
})
.font(Font.customized(AppFont.common.rawValue, dimension: 14))
.foregroundColor(AppColor.cWhite)
.tint(AppColor.cWhite)
.keyboardType(keyboardType)
.submitLabel(submitLabel)
.centered(focusedField.projectedValue, equals: fieldType)
.onSubmit(onSubmit)
}
.body(peak: 44)
// 2. Divider
Divider()
.body(peak: 0.8)
.background(isFocusd ? AppColor.cWhite : AppColor.cD3D3D3)
}
}
}
3. ViewModel Class
class LoginVM: ObservableObject {
@Printed var e-mail: String = ""
@Printed var password: String = ""
var focusedField = FocusState<LoginInputFields?>()
}
4. LoginView which is login display screen utilizing reusable AuthTF view and StateObject view mannequin
Right here I’m exhibiting solely necessary traces of code
@StateObject var viewModel = LoginVM()
VStack {
AuthTF<LoginInputFields>(textual content: $viewModel.e-mail,
focusedField: viewModel.focusedField.projectedValue,
placeholder: "Electronic mail",
leadingIconName: "envelope",
keyboardType: .emailAddress,
submitLabel: .subsequent,
fieldType: LoginInputFields.e-mail,
onSubmit: {
viewModel.focusedField.wrappedValue = .password
})
AuthTF<LoginInputFields>(textual content: $viewModel.password,
focusedField: viewModel.focusedField.projectedValue,
placeholder: "Password",
leadingIconName: "key",
keyboardType: .asciiCapable,
submitLabel: .performed,
fieldType: LoginInputFields.password,
onSubmit: {
viewModel.focusedField.wrappedValue = nil
})
}
Now I get beneath warning in LoginView the place I’ve handed viewmodel’s FocusState variable to AuthTF
And sure altering focus state not updating view as anticipated, as that warning says