Created
June 3, 2018 16:09
-
-
Save alfianlosari/a885ac13d50e5fa2583b285974ba4e6d to your computer and use it in GitHub Desktop.
ViewController
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
import UIKit | |
class ViewController: UITableViewController { | |
@IBOutlet weak var emailTextField: UITextField! | |
@IBOutlet weak var emailValidationLabel: UILabel! | |
let emailViewModel = EmailViewModel(emailModel: EmailModel(value: "")) | |
var emailTextObserver: NSObjectProtocol? | |
var isValidEmailObserver: NSObjectProtocol? | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
observeViewModel() | |
} | |
func observeViewModel() { | |
self.emailTextObserver = emailViewModel.observe(\EmailViewModel.emailTextValue, options: [.initial, .new], changeHandler: { [weak self] (_, change) in | |
self?.emailTextField.text = change.newValue | |
}) | |
self.isValidEmailObserver = emailViewModel.observe(\EmailViewModel.isValidValue, options: [.initial, .new], changeHandler: { [weak self] (_, change) in | |
guard let strongSelf = self else { return } | |
let isValid = change.newValue ?? false | |
self?.emailValidationLabel.text = isValid ? "Email is valid" : "Email is invalid" | |
self?.emailValidationLabel.textColor = isValid ? strongSelf.view.tintColor : .red | |
}) | |
self.emailTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) | |
} | |
@objc func textFieldDidChange(_ sender: UITextField) { | |
self.emailViewModel.updateEmailTextValue(self.emailTextField.text ?? "") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment