title: Obj-C UIDownpicker will fill another textfield with another value during scrolls
body: <p>My code below will fetch country name and country code from server and store into <code>2 NSMutablleMArray</code>, <code>countryMArray</code> and <code>codeMArray</code>code. When user tap the <code>txtCountry UITextField</code> It will call a <code>down picker</code> and when user select the country and hit Done, it will based on index and get the <code>Country Code from codeMArray</code> and put the code in <code>txtCode UITexField</code>. </p>
  
  <p>Instead of this way, I was wondering how to straight away fill <code>txtCode UITextfield</code> when scrolling the <code>down picker</code>. Something like the pic below. Instead of getting the user to hit done. When user scrolls the <code>down picker Country Name</code> the <code>txtCode UITexField</code> will be autofilled with the <code>Code</code>. Is there ways to do that. </p>
  
  <h1>Added the following code in *</h1>
  
  <p>I added downpicker.m and downpicker.h and also the code in * but it never triggers. Please help, thank you.</p>
  
  <p><a href="https://i.stack.imgur.com/Mi9ru.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mi9ru.png" alt="When scroll to Malaysia auto fill txtCode with Malaysia Country Code "></a></p>
  
  <p><a href="https://i.stack.imgur.com/nxsHz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nxsHz.png" alt="When scroll to China auto fill txtCode with China Country Code "></a></p>
  
  <h1>RootViewController.h</h1>
  
  <pre><code>#import &lt;UIKit/UIKit.h&gt;
  #import "LoginViewController.h"
  #import &lt;DownPicker/UIDownPicker.h&gt;
  
  @protocol LoginViewProtocol &lt;NSObject&gt;
  
  - (void)dismissAndLoginView;
  
  @end
  
  @interface RootViewController : UIViewController     &lt;UITextFieldDelegate,UITableViewDelegate&gt;
  @property (strong, nonatomic) IBOutlet UITextField *txtCountry;
  @property (weak, nonatomic) IBOutlet UIDownPicker *downCountry;
  @property (strong, nonatomic) IBOutlet UITextField *txtCode;
  @property (strong, nonatomic) IBOutlet UITextField *txtPhone;
  @property (strong, nonatomic) NSMutableArray *countryMArray;
  @property (strong, nonatomic) NSMutableArray *codeMArray;
  @property (nonatomic) DownPicker *pickerCountry;
  
  @end
  </code></pre>
  
  <h1>RootViewController.m</h1>
  
  <pre><code>#import "RootViewController.h"
  #import &lt;QuartzCore/QuartzCore.h&gt;
  
  @interface RootViewController (){
      NSString *sURL,*sResponseData, *sRemaining;
      NSString *sCode;
  
  }
  @end
  
  @implementation RootViewController
  
  @synthesize loginView;
  @synthesize txtCountry,txtCode,txtPhone;
  @synthesize countryMArray;
  @synthesize codeMArray;
  
  - (void)viewDidLoad
  {
      [super viewDidLoad];
  
      UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
  
      [self.view addGestureRecognizer:tap];
  
      //=== Initiallize the Mutable Array
      countryMArray = [[NSMutableArray alloc] init];
      codeMArray = [[NSMutableArray alloc] init];
  
      //=== Initialize the responseData Mutable Data
      self.responseData = [NSMutableData data];
  
      //=== Pass the string to server to get the return Country response.write
      appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
      sURL = @"https://www.share-fitness.com";
      sURL = [sURL stringByAppendingString:@"/apps/getcountry.asp?"];
  
      NSURLRequest *requestCountry = [NSURLRequest requestWithURL:[NSURL URLWithString:sURL]];
  
      (void) [[NSURLConnection alloc] initWithRequest:requestCountry delegate:self];
  
      //=== Pass the string to server to get the return CountryCode
      sURL = @"https://www.share-fitness.com";
      sURL = [sURL stringByAppendingString:@"/apps/getctcode.asp?"];
  
      NSURLRequest *requestCode = [NSURLRequest requestWithURL:[NSURL URLWithString:sURL]];
  
      (void) [[NSURLConnection alloc] initWithRequest:requestCode delegate:self];
  
      //=== Initialie the picker ====
      self.pickerCountry = [[DownPicker alloc] initWithTextField:self.txtCountry withData:countryMArray];
  
      [self.pickerCountry addTarget:self
                         action:@selector(pickerClicked:)
               forControlEvents:UIControlEventValueChanged];
  
  }
  
  //**** ADDED the following but will never trigger ?
   - (void)pickerView:(UIDownPicker *)pickerCountry didSelectRow:(NSInteger)row inComponent:(NSInteger)component
  {
      sCode = [codeMArray objectAtIndex:row];
      txtCode.text = [@"+"stringByAppendingString:sCode];
  }
  //**********************
   //=== Pick the countryCode, when Country is selected based on Array Index
   -(void)pickerClicked:(id)dp {
  
      NSString* selectedValue = [self.pickerCountry text];
  
      for ( int i = 0 ; i &lt; countryMArray.count; i++) {
  
          NSString*item = [countryMArray objectAtIndex:i];
  
          if([item isEqualToString:selectedValue])
          {
              sCode = [codeMArray objectAtIndex:i];
              txtCode.text = [@"+"stringByAppendingString:sCode];
  
              break;
          }
  
      }
  }
  </code></pre>
  
  <h1>Downpicker.h</h1>
  
  <pre><code>#import &lt;UIKit/UIKit.h&gt;
  
  @interface DownPicker : UIControl&lt;UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate&gt;
  {
      UIPickerView* pickerView;
      IBOutlet UITextField* textField;
      NSArray* dataArray;
      NSString* placeholder;
      NSString* placeholderWhileSelecting;
      NSString* toolbarDoneButtonText;
      NSString* toolbarCancelButtonText;
      UIBarStyle toolbarStyle;
  }
  
  @property (nonatomic) NSString* text;
  @property (nonatomic) NSInteger selectedIndex;
  
  -(id)initWithTextField:(UITextField *)tf;
  -(id)initWithTextField:(UITextField *)tf withData:(NSArray*) data;
  
  @property (nonatomic) BOOL shouldDisplayCancelButton;
  
  /**
  Sets an alternative image to be show to the right part of the textbox (assuming that showArrowImage is set to TRUE).
   @param image
   A valid UIImage
  */
  -(void) setArrowImage:(UIImage*)image;
  
  -(void) setData:(NSArray*) data;
  -(void) setPlaceholder:(NSString*)str;
  -(void) setPlaceholderWhileSelecting:(NSString*)str;
  -(void) setAttributedPlaceholder:(NSAttributedString *)attributedString;
  -(void) setToolbarDoneButtonText:(NSString*)str;
  -(void) setToolbarCancelButtonText:(NSString*)str;
  -(void) setToolbarStyle:(UIBarStyle)style;
  
  /**
   TRUE to show the rightmost arrow image, FALSE to hide it.
   @param b
   TRUE to show the rightmost arrow image, FALSE to hide it.
  */
  -(void) showArrowImage:(BOOL)b;
  
  -(UIPickerView*) getPickerView;
  -(UITextField*) getTextField;
  
  /**
  Retrieves the string value at the specified index.
  @return
  The value at the given index or NIL if nothing has been selected yet.
  */
  -(NSString*) getValueAtIndex:(NSInteger)index;
  
  /**
  Sets the zero-based index of the selected item: -1 can be used to clear        selection.
  @return
  The value at the given index or NIL if nothing has been selected yet.
  */
  -(void) setValueAtIndex:(NSInteger)index;
  @end
  </code></pre>
  
  <h1>Downpicker.m</h1>
  
  <pre><code>#import "DownPicker.h"
  
  @implementation DownPicker
  {
      NSString* _previousSelectedString;
  }
  
  -(id)initWithTextField:(UITextField *)tf
  {
      return [self initWithTextField:tf withData:nil];
  }
  
  -(id)initWithTextField:(UITextField *)tf withData:(NSArray*) data
  {
       self = [super init];
       if (self) {
          self-&gt;textField = tf;
          self-&gt;textField.delegate = self;
  
          // set UI defaults
          self-&gt;toolbarStyle = UIBarStyleDefault;
  
          // set language defaults
          self-&gt;placeholder = @"Tap to choose...";
          self-&gt;placeholderWhileSelecting = @"Pick an option...";
          self-&gt;toolbarDoneButtonText = @"Done";
          self-&gt;toolbarCancelButtonText = @"Cancel";
  
          // hide the caret and its blinking
          [[textField valueForKey:@"textInputTraits"]
           setValue:[UIColor clearColor]
           forKey:@"insertionPointColor"];
  
          // set the placeholder
          self-&gt;textField.placeholder = self-&gt;placeholder;
  
          // setup the arrow image
          UIImage* img = [UIImage imageNamed:@"downArrow.png"];   // non-CocoaPods
          if (img == nil) img = [UIImage imageNamed:@"DownPicker.bundle/downArrow.png"]; // CocoaPods
          if (img != nil) self-&gt;textField.rightView = [[UIImageView alloc] initWithImage:img];
          self-&gt;textField.rightView.contentMode = UIViewContentModeScaleAspectFit;
          self-&gt;textField.rightView.clipsToBounds = YES;
  
          // show the arrow image by default
          [self showArrowImage:YES];
  
          // set the data array (if present)
          if (data != nil) {
              [self setData: data];
          }
  
          self.shouldDisplayCancelButton = YES;
      }
      return self;
  }
  
  - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
  {
      return (interfaceOrientation == UIInterfaceOrientationPortrait);
  }
  
  - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
  {
      return 1;
  }
  
  - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
  {
      self-&gt;textField.text = [dataArray objectAtIndex:row];
  }
  
   - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
   {
      return [dataArray count];
   }
  
   - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
   {
      return [dataArray objectAtIndex:row];
   }
  
   -(void)doneClicked:(id) sender
   {
      //hides the pickerView
      [textField resignFirstResponder];
  
      if (self-&gt;textField.text.length == 0 || ![self-&gt;dataArray containsObject:self-&gt;textField.text]) {
          // self-&gt;textField.text = [dataArray objectAtIndex:0];
          [self setValueAtIndex:-1];
          self-&gt;textField.placeholder = self-&gt;placeholder;
      }
      /*
      else {
          if (![self-&gt;textField.text isEqualToString:_previousSelectedString])   {
              [self sendActionsForControlEvents:UIControlEventValueChanged];
          }
      }
      */
      [self sendActionsForControlEvents:UIControlEventValueChanged];
  }
  
  -(void)cancelClicked:(id)sender
  {
      [textField resignFirstResponder]; //hides the pickerView
      if (_previousSelectedString.length == 0 || ![self-&gt;dataArray containsObject:_previousSelectedString]) {
          self-&gt;textField.placeholder = self-&gt;placeholder;
      }
      self-&gt;textField.text = _previousSelectedString;
  }
  
  - (IBAction)showPicker:(id)sender
  {
      _previousSelectedString = self-&gt;textField.text;
  
      pickerView = [[UIPickerView alloc] init];
      pickerView.showsSelectionIndicator = YES;
      pickerView.dataSource = self;
      pickerView.delegate = self;
  
      //If the text field is empty show the place holder otherwise show the last selected option
      if (self-&gt;textField.text.length == 0 || ![self-&gt;dataArray containsObject:self-&gt;textField.text])
      {
          if (self-&gt;placeholderWhileSelecting) {
              self-&gt;textField.placeholder = self-&gt;placeholderWhileSelecting;
          }
           // 0.1.31 patch: auto-select first item: it basically makes placeholderWhileSelecting useless, but
           // it solves the "first item cannot be selected" bug due to how the pickerView works.
          [self setSelectedIndex:0];
      }
       else
      {
          if ([self-&gt;dataArray containsObject:self-&gt;textField.text]) {
              [self-&gt;pickerView selectRow:[self-&gt;dataArray indexOfObject:self-&gt;textField.text] inComponent:0 animated:YES];
          }
      }
  
      UIToolbar* toolbar = [[UIToolbar alloc] init];
      toolbar.barStyle = self-&gt;toolbarStyle;
      [toolbar sizeToFit];
  
      //space between buttons
      UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                                 target:nil
                                                                                 action:nil];
  
      UIBarButtonItem* doneButton = [[UIBarButtonItem alloc]
                                 initWithTitle:self-&gt;toolbarDoneButtonText
                                 style:UIBarButtonItemStyleDone
                                 target:self
                                 action:@selector(doneClicked:)];
  
      if (self.shouldDisplayCancelButton) {
          UIBarButtonItem* cancelButton = [[UIBarButtonItem alloc]
                                       initWithTitle:self-&gt;toolbarCancelButtonText
                                       style:UIBarButtonItemStylePlain
                                       target:self
                                       action:@selector(cancelClicked:)];
  
          [toolbar setItems:[NSArray arrayWithObjects:cancelButton, flexibleSpace, doneButton, nil]];
      } else {
          [toolbar setItems:[NSArray arrayWithObjects:flexibleSpace, doneButton, nil]];
      }
  
      //custom input view
      textField.inputView = pickerView;
      textField.inputAccessoryView = toolbar;  
  }
  
  - (BOOL)textFieldShouldBeginEditing:(UITextField *)aTextField
  {
      if ([self-&gt;dataArray count] &gt; 0) {
          [self showPicker:aTextField];
          return YES;
      }
      return NO;
  }
  
  - (void)textFieldDidEndEditing:(UITextField *)aTextField {
      // [self doneClicked:aTextField];
      aTextField.userInteractionEnabled = YES;
  }
  
  - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:  (NSRange)range replacementString:(NSString *)string
  {
      return NO;
  }
  
  -(void) setData:(NSArray*) data
  {
      dataArray = data;
      NSLog(@" This is the data : %@ ", dataArray);
  }
  
  -(void) showArrowImage:(BOOL)b  
  {
      if (b == YES) {
        // set the DownPicker arrow to the right (you can replace it with any 32x24 px transparent image: changing size might give different results)
      self-&gt;textField.rightViewMode = UITextFieldViewModeAlways;
      }
      else {
          self-&gt;textField.rightViewMode = UITextFieldViewModeNever;
      }
  }
  
  -(void) setArrowImage:(UIImage*)image
  {
      [(UIImageView*)self-&gt;textField.rightView setImage:image];
  }
  
  -(void) setPlaceholder:(NSString*)str
  {
      self-&gt;placeholder = str;
      self-&gt;textField.placeholder = self-&gt;placeholder;
  }
  
  -(void) setPlaceholderWhileSelecting:(NSString*)str
  {
      self-&gt;placeholderWhileSelecting = str;
  }
  
  -(void) setAttributedPlaceholder:(NSAttributedString *)attributedString
  {
      self-&gt;textField.attributedPlaceholder = attributedString;
  }
  
  -(void) setToolbarDoneButtonText:(NSString*)str
  {
      self-&gt;toolbarDoneButtonText = str;
  }
  
  -(void) setToolbarCancelButtonText:(NSString*)str
  {
      self-&gt;toolbarCancelButtonText = str;
  }
  
  -(void) setToolbarStyle:(UIBarStyle)style;
  {
      self-&gt;toolbarStyle = style;
  }
  
  -(UIPickerView*) getPickerView
  {
      return self-&gt;pickerView;
  }
  
  -(UITextField*) getTextField
  {
      return self-&gt;textField;
  }
  
  -(NSString*) getValueAtIndex:(NSInteger)index
  {
      return (self-&gt;dataArray.count &gt; index) ? [self-&gt;dataArray    objectAtIndex:index] : nil;
  }
  
  -(void) setValueAtIndex:(NSInteger)index
  {
      if (index &gt;= 0) [self pickerView:nil didSelectRow:index inComponent:0];
      else [self setText:nil];
  }
  
  /**
   Getter for text property.
   @return
   The value of the selected item or NIL NIL if nothing has been selected yet.
   */
  - (NSString*) text {
      return self-&gt;textField.text;
  }
  
  /**
   Setter for text property.
   @param txt
   The value of the item to select or NIL to clear selection.
   */
  - (void) setText:(NSString*)txt {
      if (txt != nil) {
          NSInteger index = [self-&gt;dataArray indexOfObject:txt];
          if (index != NSNotFound) [self setValueAtIndex:index];
      }
      else {
          self-&gt;textField.text = txt;
      }
  }
  
  /**
   Getter for selectedIndex property.
   @return
   The zero-based index of the selected item or -1 if nothing has been selected yet.
   */
  - (NSInteger)selectedIndex {
      NSInteger index = [self-&gt;dataArray indexOfObject:self-&gt;textField.text];
      return (index != NSNotFound) ? (NSInteger)index : -1;
  }
  
  /**
   Setter for selectedIndex property.
   @param index
   Sets the zero-based index of the selected item using the setValueAtIndex method:    -1 can be used to clear selection.
   */
  - (void)setSelectedIndex:(NSInteger)index {
      [self setValueAtIndex:(NSInteger)index];
  }
  
  @end
  </code></pre>