设置委托时,RxSwift UIPicker崩溃

时间:2017-11-23 07:46:22

标签: swift rx-swift

所以我为我的应用设置了一个uipicker,代码如下

self.leftPicker.rx.setDelegate(self).disposed(by: bag)
        Driver.just([1, 2, 3, 4, 5, 6])
            .drive(leftPicker.rx.items){
                index, item, view in
                if let label = view as? UILabel{
                    return label
                }
                let label = UILabel()
                label.font = UIFont(name: SRFonts.asap_regular.fontName, size: 13)
                label.textAlignment = .center
                label.text = "\(item)"
                return label
        }
        .disposed(by: bag)

如果我这样做,应用程序将崩溃,说有一个冲突的委托...所以如果我要删除

self.leftPicker.rx.setDelegate(self).disposed(by: bag)

崩溃消失了......

但问题是,我希望设置uipicker行的高度,没有委托,我似乎无法设置高度

func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 44
    }

这真的很奇怪,因为它通常适用于RxTableView和RxCollectionView。

任何人都知道出了什么问题?

1 个答案:

答案 0 :(得分:1)

立即引起我注意的是你传递一个数组而不是数组数组。请尝试 [[1,2,3,4,5,6]]

let data: PickerViewAdapter.Element = [
        ["0", "1", "2"],
        ["a", "b", "c"]
    ]

Observable.just(data)
  .bind(to: pickerView.rx.items(adapter: PickerViewAdapter()))
  .disposed(by: self.disposeBag)

final class PickerViewAdapter: NSObject
    , UIPickerViewDataSource
    , UIPickerViewDelegate
    , RxPickerViewDataSourceType
    , SectionedViewDataSourceType {

    typealias Element = [[CustomStringConvertible]]
    private var items: [[CustomStringConvertible]] = []

    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
    }

    /* ... */

修改

此外,在我的示例中,Adapter是委托。如果你没有指定一个,它将自动创建委托(见https://github.com/ReactiveX/RxSwift/blob/master/RxCocoa/iOS/UIPickerView%2BRx.swift),因此发生冲突。

使用您的自定义适配器类尝试 .bind(to:pickerView.rx.items(adapter:PickerViewAdapter()))