UIPickerView select first row programmatically UIPickerView select first row programmatically xcode xcode

UIPickerView select first row programmatically


Swift 3+

func textFieldDidBeginEditing(_ textField: UITextField) {    if textField == yourTextField{        self.yourPickerView.selectRow(0, inComponent: 0, animated: true)        self.pickerView(yourPickerView, didSelectRow: 0, inComponent: 0)    }}func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {//Do all the stuff to populate the TextField}


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 !


I had a same problem. My solution was this:

-(void)textFieldDidBeginEditing:(UITextField *)textField{    // Only for the text field with the picker    if (textField == self.yourTextField)    {        // Select the first row programmatically         [self.categoriesPicker selectRow:0 inComponent:0 animated:YES];        // The delegate method isn't called if the row is selected programmatically        [self pickerView:self.categoriesPicker didSelectRow:0 inComponent:0];    }}- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{    //Do all the stuff to populate the TextField}