Last active
March 27, 2021 11:41
-
-
Save bocato/4c7b0449a7ae64aff2de9494b6cd64d2 to your computer and use it in GitHub Desktop.
mvvm_form_3.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
final class ExampleViewModel: StateBindingViewModel<ExampleState> { | |
// MARK: - Public Methods | |
func performSignUp() { | |
if state.password.count < 6 { | |
state.passwordError = "The Password should have at least 6 characters." | |
} | |
// Do aditional validations and send the data to the server... | |
} | |
// MARK: - StateBindingViewModel Conformance | |
override func stateWillChangeValue<Value>( | |
_ keyPath: PartialKeyPath<ExampleState>, | |
newValue: Value | |
) -> Bool where Value: Equatable { | |
switch (keyPath, newValue) { | |
case let (\ExampleState.password, newValue as String): | |
state.passwordError = nil | |
return newValue.count <= 12 | |
default: | |
return true | |
} | |
} | |
override func onStateChange(_ keyPath: PartialKeyPath<ExampleState>) { | |
state.isSignUpButtonEnabled = isValidForm() | |
} | |
// MARK: - Private Methods | |
private func isValidForm() -> Bool { | |
return !state.email.isEmpty && !state.password.isEmpty | |
} | |
} | |
struct ExampleView: View { | |
// MARK: - Dependencies | |
@StateObject var viewModel: ExampleViewModel | |
// MARK: - View Content | |
var body: some View { | |
Form { | |
Section(header: Text("E-mail")) { | |
TextField( | |
"example@mail.com", | |
text: viewModel.binding(\.email) | |
) | |
} | |
Section(header: Text("Password")) { | |
SecureField( | |
"xxxxxx", | |
text: viewModel.binding(\.password) | |
) | |
if let passwordError = viewModel.state.passwordError { | |
Text(passwordError) | |
.font(.title3) | |
.foregroundColor(.red) | |
} | |
} | |
Button( | |
"Sign Up", | |
action: viewModel.performSignUp | |
) | |
.disabled(viewModel.state.isSignUpButtonEnabled == false) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment