Search code examples
iosswiftuipickerview

Why isn't UIPickerView showing rows? swift


I'm trying to make a single UIPickerView with 2 components, each with a different amount of rows. I thought that I could base the row number per component on the index of the component, but when I run my app the UIPickerView displays only one single blank row and doesn't allow scrolling.

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

// grades is a 2D array
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return grades[component].count
}

// level and letter are predefined ints
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if component == 0 {
        level = row
    }else if component == 1 {
        letter = row
    }
    return ""
}

EDIT:

This is my viewDidLoad()

override func viewDidLoad() {
    super.viewDidLoad()
    pickerView.dataSource = self;
    pickerView.delegate = self;
}

Solution

  • I believe you should return non-empty title to make it work

    ...
    
    // level and letter are predefined ints
    
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    
        if component == 0 {
            level = row
        } else if component == 1 {
            letter = row
        }
        return "Component: \(component) Row: \(row)" // whatever string you want to display
    }