RxSwift MVVM 实现查询
Posted
技术标签:
【中文标题】RxSwift MVVM 实现查询【英文标题】:RxSwift MVVM implemention inquire 【发布时间】:2018-08-01 01:25:43 【问题描述】:我有两个UITextField
和一个UITableView
在一个UIViewController
中。这个UIViewController
的 ViewModel 公开了一个 Observable 作为表视图数据源。两个UITextField
从用户那里获取参数并刷新表视图Observable。 UITextField
使用 UIPickerView
作为 InputView,而 UIPickerViews
使用自定义类作为适配器。
在 UIViewController 中:
//bind the adapter to the UIPickerView
self.viewModel.dateList.bind(to: self.datePickerView.rx.items(adapter: self.viewModel.pickerViewAdapter)).disposed(by: rx.disposeBag)
在 ViewModel 中:
let dateList = Observable.just([[Int](0...1), [Int](1...12)])
final class PickerViewViewAdapter
: NSObject
, UIPickerViewDataSource
, UIPickerViewDelegate
, RxPickerViewDataSourceType
, SectionedViewDataSourceType
typealias Element = [[Int]]
private var items: [[Int]] = []
var activeTextField:UITextField!
func model(at indexPath: IndexPath) throws -> Any
return items[indexPath.section][indexPath.row]
func numberOfComponents(in pickerView: UIPickerView) -> Int
return items.count
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
return items[component].count
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView
let label = UILabel()
if component == 0
label.text = "\(2018 - items[component][row])"
else
label.text = "\(items[component][row])"
label.font = UIFont.preferredFont(forTextStyle: .title1)
label.textAlignment = .center
return label
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
///
/// Need to update the UITextField.text in a specific form
///
func pickerView(_ pickerView: UIPickerView, observedEvent: Event<Element>)
Binder(self) (adapter, items) in
adapter.items = items
pickerView.reloadAllComponents()
.on(observedEvent)
用户从UIPickerView
中选择后,我需要以特定形式更新UITextField.text
,然后将这些文本用作API的参数。
我应该如何在 MVVM 中以 Reactive 方式执行此操作?
【问题讨论】:
【参考方案1】:我不确定您的代码中发生了什么,但也许这会有所帮助:
let items = Observable.just(Calendar.current.monthSymbols)
let pickerView = UIPickerView()
textField.inputView = pickerView
// this pipe displays the items in the picker view
items
.bind(to: pickerView.rx.itemTitles) $1
.disposed(by: bag)
// this pipe displays the picked item in the text field
Observable.combineLatest(items, pickerView.rx.itemSelected) $0[$1.row]
.bind(to: textField.rx.text)
.disposed(by: bag)
【讨论】:
以上是关于RxSwift MVVM 实现查询的主要内容,如果未能解决你的问题,请参考以下文章
RxSwift 和 MVVM:observable 在没有绑定的情况下无法执行
MVVM + RXSwift+ Coordinator 如何设置数据?