Jonesopolis Jonesopolis - 1 year ago 185
iOS Question

UIPickerView select first row programmatically

There are a lot of questions like this, but I believe my case is unique.

I have a pickerview that pops up when a textbox is clicked inside. The user selects their location in the pickerview, and it's put into the textbox.

When opening the pickerview, the slider is on the first element, but if i click the done button to minimize the pickerview, that no element is selected (i.e. you must scroll down and back up to select the first element)

I've tried

[pickerView selectRow:0 inComponent:0 animated:YES];

and various combinations of it, but it only puts the slider on that element, again not actually selecting it.

Some answers said to apply the above code in the viewDidLoad() method, but unfortunately I'm pulling the location array in from a web service and cannot do that.

Ideally, I'd like to work as - the user clicks in the textbox, the pickerview pops up as normal, if at that point the done button is clicked, the first item is selected.

Thankyou in advance

Answer Source

Here is something you can try :

Set a var in your @interface, something like NSString *selectedString;.

When you init your UIPickerView (in pickerView:titleForRow:forComponent:), when you set the title for the row 0, set selectedString with the same string as the title of the row #0. Then, in pickerView:didSelectRow:inComponent:, set selectedString with the appropiate string :

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

    // Some stuff

    // Assuming "yourDataArray" contains your strings
    selectedString = [yourDataArray objectAtIndex:row];


Then, when you call the method triggered by the push of the "done" button, use selectedString to set the text.

Hope this works out for you !

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download