即使在重新查询后,UIPickerView也不显示数据

时间:2015-12-29 12:14:25

标签: ios swift swift2 uipickerview rx-swift

我们说我有一群狗private var dogs: Observable<[Dogs]>。每次生成一个新值时,我会调用块来创建一个新的dataSource并委托我的UIPickerView,然后在块中我调用pickerView.reloadAllComponents(),但我的视图显示为空的pickerView,即使查询dataSource和delegate。

示例代码:

self.dataStream
        .subscribeNext {
            self.dataSource = PickerViewDataSource(data: $0)
            self.pickerView.dataSource = self.dataSource
            self.delegate = PickerViewDelegate(data: $0, selectedRow: self._selectedRowStream)
            self.pickerView.delegate = self.delegate
            self.pickerView.reloadAllComponents()
        }.addDisposableTo(self.disposeBag)

调试dataSource和委托我知道这些是被查询的,我在UIViewController中保留dataSource和委托引用的原因是由于UIPickerView为这些保留了弱引用。

这是我尝试过的最后一个策略,但仍然得到了相同的结果。任何帮助,将不胜感激。感谢。

更新

DogPickerViewDataSource:

class DogPickerViewDataSource: NSObject, UIPickerViewDataSource {

    private var dogs: [Dog]

    init(
        dogs: [Dog]
    ) {
        self.dogs = dogs
    }

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return dogs.count
    }
}

DogPickerViewDelegate:

class DogPickerViewDelegate: NSObject, UIPickerViewDelegate {

    private var selectedRow: BehaviorSubject<Int>
    private var dogs: [Dog]

    init(
        dogs: [Dog],
        selectedRow: BehaviorSubject<Int>
    ) {
        self.dogs = dogs
        self.selectedRow = selectedRow
    }

    func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
        let dogName = (self.dogs[row].name)!
        return NSAttributedString(string: dogName)
    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        self.selectedRow.onNext(row)
    }
}

1 个答案:

答案 0 :(得分:0)

如果我理解正确,请在viewDidLoad上使用新的委托和数据源初始化pickerView,调用reloadAllComponents并期望所有内容都应正确显示。但是你仍然在显示前一个视图控制器的pickerView。您应该尝试在以前的视图控制器的viewWillDisappear方法中隐藏选择器视图,并在新视图控制器的viewDidAppear方法中显示新的视图。