JenniO
JenniO

Reputation: 81

UIPickerView not displaying data Swift 3

I have the relevant functions to JUST display the data in my picker here, the picker is being added to the view when the relevant function is called, but it is blank. This is my class:

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) {
}

I have a protocol method but it doesn't add anything.

I call it in a different ViewController:

fileprivate let statePicker = StatePickerView()

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

and then when a button is clicked, it is added as a subview:

    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)
    }
}

I have combed through and tried virtually every relevant thing on Stack Overflow already but I am stumped. My titleForRow function never even gets hit. Where is my mistake?

Upvotes: 1

Views: 2013

Answers (1)

JenniO
JenniO

Reputation: 81

Fixed: Instead of the class inheriting from UIPickerView, I changed it to UIView. I instantiated an instance of a UIPicker, then added the picker to the view on instantiation of the class.

For the delegation, I did the following in the override init method:

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

Upvotes: 3

Related Questions