Search code examples
iosswiftuipickerview

UIPickerView - 1st row selection does not call didSelectRow (in Swift)


I have a UIPickerView and when the user selects a row and press on a button called 'Start' the row selected will start a particular method.

To detect the selected row in the picker(and update the variable), I use the following code:

    var picked = 15

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

        if row == 0 {
            picked = 1
       }
        else if row == 1 {
           picked = 2
       }
        else if row == 2 {
           picked = 3
       }
    }

This method is triggered whenever the user makes a CHANGE to the picker selection. But if the user does not select any value on the picker (bc the user want to select the 1st option which is already selected), this method is not called.

I know there is already a well answered question about this issue, but this for Objective C (uipickerview-1st-row-selection-does-not-call-didselectrow). I want the answer for Swift, bc I have no OBjective C skills.

So my question: How can I let the 1st option of the picker, which is already selected, be detected as selected row by the user? (So this already-selected-row will update the variable)

I added to the code in viewDidAppear:

        picker1.selectRow(2, inComponent: 0, animated: true)
        // scrolls the specified row to center.

But this only SHOWS the specified row, but not RETURNS the specified row for the didSelectRow func. So this doesnt do it for me


Solution

  • The documentation says (at https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIPickerViewDelegate_Protocol/index.html#//apple_ref/occ/intfm/UIPickerViewDelegate/pickerView:didSelectRow:inComponent:) : "Called by the picker view when the user selects a row in a component.". Thus, you should rather query the state of the picker itself when it's getting dismissed via - (NSInteger)selectedRowInComponent:(NSInteger)component / func selectedRowInComponent(_ component: Int) -> Int .