Search code examples
iosswiftxcodeuipickerview

? returned when trying to load data source into UIPickerView


I am trying to load 1 - 15 into a Picker View but with my code, it return 15 question marks. What am I doing wrong in my code below? I have followed a guide for it but this does not seem to work. It must be something small that I have to adjust to make this work.

class NewDaySplitViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

@IBOutlet weak var picker: UIPickerView!

var pickerData: [String] = [String]()

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    self.picker.delegate = self
    self.picker.dataSource = self

    pickerData = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"]
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

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

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

// The data to return for the row and component (column) that's being passed in
private func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return pickerData[row]
}


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

Solution

  • Your delegate method titleForRow has incorrect signature.

    Try to use Xcode auto-complete:

    Start typing picker...

    Then a list will appear:

    enter image description here

    Select titleForRow method, press enter and put your code like:

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return pickerData[row]
    }
    

    Errors on signature:

    The method isn't private and you don't have _ as first parameter.