gpt4 book ai didi

ios - RxSwift MVVM 实现查询

转载 作者:行者123 更新时间:2023-11-28 07:43:19 24 4
gpt4 key购买 nike

我在一个 UIViewController 中有两个 UITextField 和一个 UITableView。此 UIViewController 的 ViewModel 将一个 Observable 公开为 TableView 数据源。这两个 UITextField 从用户那里获取参数并刷新 TableView 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)

在 View 模型中:

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 方式执行此操作?

最佳答案

我不确定您的代码中发生了什么,但也许这会有所帮助:

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)

关于ios - RxSwift MVVM 实现查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51624130/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com