UIPickerView不显示数据Swift 3

时间:2017-06-27 16:37:11

标签: swift3 uiviewcontroller uipickerview

我有相关的功能只能在我的选择器中显示数据,当调用相关函数时,选择器被添加到视图中,但它是空白的。这是我的班级:

class StatePickerView : UIPickerView, UIPickerViewDelegate, UIPickerViewDataSource {

private let states = ["Illinois", "Arizona", "Indiana", "New York", "Oklahoma", "California", "Kentucky", "North Carolina", "Texas", "Massachisetts", "Ohio", "Wisonsin"]

var statePickerDelegate: StatePickerDelegate?

override init(frame: CGRect) {
    super.init(frame: frame)
    self.backgroundColor = .magenta

}


required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    debugPrint("numberOfComponnets")
    return 1
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    switch component {
    case 0:
        return states[row]
    default:
        return "row"
    }

}

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

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
}

我有一个协议方法但它没有添加任何东西。

我在另一个ViewController中调用它:

fileprivate let statePicker = StatePickerView()

override func viewDidLoad() {
    super.viewDidLoad()
    self.statePicker.statePickerDelegate = self
}

然后当点击一个按钮时,它会被添加为子视图:

    func changeButtonTapped() {
    self.changeButtonClicked = true
    self.statePicker.statePickerDelegate = self
    self.statePicker.reloadAllComponents()

    self.view.addSubview(self.statePicker)
    self.statePicker.snp.remakeConstraints {
        $0.top.equalTo(self.currentStateView.snp.bottom)
        $0.bottom.equalTo(self.view.snp.bottom)
        $0.width.equalTo(self.view.snp.width)
        $0.centerX.equalTo(self.view.snp.centerX)
    }
}

我已经梳理过并且已经在Stack Overflow上尝试了几乎所有相关的东西,但我很难过。我的titleForRow函数甚至没有被击中。我的错误在哪里?

1 个答案:

答案 0 :(得分:2)

修正: 我将其更改为UIView,而不是继承自UIPickerView的类。我实例化了一个UIPicker的实例,然后在实例化该类时将选择器添加到视图中。

对于委托,我在override init方法中执行了以下操作:

    self.pickerView.delegate = self
    self.pickerView.dataSource = self