我认为您缺少其中的适当rx
属性,FormElement
这将使您能够将 UI 事件绑定到要在 ViewModel 中执行的验证。
首先FormElement
,textInput
应该公开一个文本 Variable
和button
一个启用 Driver
的。我做了这个区分是为了展示在第一种情况下您想要使用 UI 事件,而在第二种情况下您只想更新 UI。
enum FormElement {
case textInput(placeholder: String, text: Variable<String?>)
case button(title: String, enabled:Driver<Bool>, tapped:PublishRelay<Void>)
}
我冒昧地添加了一个点击事件,当按钮最终启用时,您可以执行您的业务逻辑!
继续前进ViewModel
,我只公开了View
需要知道的内容,但在内部我应用了所有必要的运算符:
class FormViewModel {
// what ViewModel exposes to view
let formElementsVariable: Variable<[FormElement]>
let registerObservable: Observable<Bool>
init() {
// form element variables, the middle step that was missing...
let username = Variable<String?>(nil) // docs says that Variable will deprecated and you should use BehaviorRelay...
let password = Variable<String?>(nil)
let passwordConfirmation = Variable<String?>(nil)
let enabled: Driver<Bool> // no need for Variable as you only need to emit events (could also be an observable)
let tapped = PublishRelay<Void>.init() // No need for Variable as there is no need for a default value
// field validations
let usernameValidObservable = username
.asObservable()
.map { text -> Bool in !(text?.isEmpty ?? true) }
let passwordValidObservable = password
.asObservable()
.map { text -> Bool in text != nil && !text!.isEmpty && text!.count > 5 }
let passwordConfirmationValidObservable = passwordConfirmation
.asObservable()
.map { text -> Bool in text != nil && !text!.isEmpty && text!.count > 5 }
let passwordsMatchObservable = Observable.combineLatest(password.asObservable(), passwordConfirmation.asObservable())
.map({ (password, passwordConfirmation) -> Bool in
password == passwordConfirmation
})
// enable based on validations
enabled = Observable.combineLatest(usernameValidObservable, passwordValidObservable, passwordConfirmationValidObservable, passwordsMatchObservable)
.map({ (usernameValid, passwordValid, passwordConfirmationValid, passwordsMatch) -> Bool in
usernameValid && passwordValid && passwordConfirmationValid && passwordsMatch // return true if all validations are true
})
.asDriver(onErrorJustReturn: false)
// now that everything is in place, generate the form elements providing the ViewModel variables
formElementsVariable = Variable<[FormElement]>([
.textInput(placeholder: "username", text: username),
.textInput(placeholder: "password", text: password),
.textInput(placeholder: "password, again", text: passwordConfirmation),
.button(title: "create account", enabled: enabled, tapped: tapped)
])
// somehow you need to subscribe to register to handle for button clicks...
// I think it's better to do it from ViewController because of the disposeBag and because you probably want to show a loading or something
registerObservable = tapped
.asObservable()
.flatMap({ value -> Observable<Bool> in
// Business login here!!!
NSLog("Create account!!")
return Observable.just(true)
})
}
}
最后,在你的View
:
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
private let disposeBag = DisposeBag()
var formViewModel: FormViewModel = FormViewModel()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "TextInputTableViewCell", bundle: nil), forCellReuseIdentifier: "TextInputTableViewCell")
tableView.register(UINib(nibName: "ButtonTableViewCell", bundle: nil), forCellReuseIdentifier: "ButtonTableViewCell")
// view subscribes to ViewModel observables...
formViewModel.registerObservable.subscribe().disposed(by: disposeBag)
formViewModel.formElementsVariable.asObservable()
.bind(to: tableView.rx.items) {
(tableView: UITableView, index: Int, element: FormElement) in
let indexPath = IndexPath(row: index, section: 0)
switch element {
case .textInput(let placeholder, let defaultText):
let cell = tableView.dequeueReusableCell(withIdentifier: "TextInputTableViewCell", for: indexPath) as! TextInputTableViewCell
cell.textField.placeholder = placeholder
cell.textField.text = defaultText.value
// listen to text changes and pass them to viewmodel variable
cell.textField.rx.text.asObservable().bind(to: defaultText).disposed(by: self.disposeBag)
return cell
case .button(let title, let enabled, let tapped):
let cell = tableView.dequeueReusableCell(withIdentifier: "ButtonTableViewCell", for: indexPath) as! ButtonTableViewCell
cell.button.setTitle(title, for: .normal)
// listen to viewmodel variable changes and pass them to button
enabled.drive(cell.button.rx.isEnabled).disposed(by: self.disposeBag)
// listen to button clicks and pass them to the viewmodel
cell.button.rx.tap.asObservable().bind(to: tapped).disposed(by: self.disposeBag)
return cell
}
}.disposed(by: disposeBag)
}
}
}
希望我有所帮助!
PS。我主要是一名 Android 开发人员,但我发现你的问题(和赏金)很有趣,所以请原谅 (rx)swift 的任何粗糙边缘