self.genderSource = RxPickerViewAttributedStringAdapter<[[DKProfileOption]]>.init(components:[]) { dataSource, pickerView, components in 返回 1 } numberOfRowsInComponent: { [weak self] dataSource, pickerView, components, component in 返回自我?.genderDetail.value.count ?? 0 } attributedTitleForRow: { [weak self] dataSource, pickerView, components, row, component in 让 title:String = self?.genderDetail.value[row].title ?? “” 让 attr_title = NSAttributedString(string: title, attributes:[.font:DKAppFont.Medium.font(size: 13) ?? UIFont.systemFont(ofSize:13)]) 返回 attr_title }
这是我的 viewModel 代码。我没有完成按钮,但我想在里面添加完成按钮。也有 RxSwift 代码。
我的viewCodes在这里。
if 让 genderSource = castedViewModel.genderSource { castedViewModel 。性别 .bind(到:genderPicker.rx.items(适配器:genderSource)) .disposed(by: 包) } self.genderField?.inputView = genderPicker
我想在里面添加完成按钮。
我假设你想要这样的东西:
extension UITextField {
func setUpWithPicker<T>(elements: Observable<[T]>, description: @escaping (T) -> String) -> Observable<T> {
precondition(inputAccessoryView == nil && inputView == nil, "The text view is already set up")
let pickerView = UIPickerView()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: nil)
let toolBar = {
let result = UIToolbar()
let flexibleSapce = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
result.frame.size.height = 44
result.autoresizingMask = [.flexibleWidth]
result.items = [flexibleSapce, doneButton]
return result
}()
_ = elements
.take(until: rx.deallocating)
.bind(to: pickerView.rx.itemAttributedTitles) { _, element in
NSAttributedString(string: description(element), attributes: [.font: UIFont.systemFont(ofSize: 13)])
}
_ = doneButton.rx.tap
.take(until: rx.deallocating)
.bind(onNext: { [weak self] in
self?.resignFirstResponder()
})
inputAccessoryView = toolBar
inputView = pickerView
return doneButton.rx.tap
.withLatestFrom(pickerView.rx.modelSelected(T.self))
.compactMap { $0.first }
}
}
只需将以上内容复制/粘贴到您的代码中。你可以这样使用它:
let elements = [DKProfileOption(title: "One"), DKProfileOption(title: "Two"), DKProfileOption(title: "Three")]
textField.setUpWithPicker(elements: .just(elements), description: { $0.title })
.bind(onNext: { response in
print(response)
})
.disposed(by: disposeBag)