Sunday, March 17, 2013

How to Get/Set text in Text Field

How to set text into a Text Field object

  1. I am assuming that you have already dragged a Text Field object onto the story board.
  2. Open the ViewController.h file and paste the following code in the @interface section:

    @property (strongnonatomicIBOutlet UITextField *txbName;

  3. Open the ViewController.m file and paste the following code in the @implementation section:

    @synthesize txbName;
  4. Open the story board.
  5. Right click drag the yellow icon (with a white square in it) on the bottom of the screen and drag it to the text field.
  6. Once you drop, a menu will popup. Choose txbURL.
  7. Done. Lets see if it works.
  8. To test the "set text" functionality, we will initialize it in the "page_load" sort-of function called viewDidLoad.
  9. Open the ViewController.m file and paste the following code in the viewDidLoad function:

    txbURL.text = @"Salam bhai jan";
  10. Run the code to verify results.


How to get text from a Text Field object

  1. I want to keep this focused and clutter free (don't want to put more new stuff). So I will initialize the text field by setting "init" as the value using the story board. And then on the viewDidLoad function, I will get that value (so as to show you that it works) and add an "x" in the beginning to make it as "xinit".
  2. Open story board, click on the text field and on the left side panel you will see the properties. Change the text from "Text" (it's grayed out) to "init". Incase you are not able to see the properties you may need to switch to the Attributes Inspector tab. 
  3. The story board shows init as the initial value.
  4. Now we will change the code that we wrote in step-9 in the above section. Change it to:

        NSString *strModified = @"x";
        strModified = [strModified stringByAppendingString:txbURL.text];
        
        txbURL.text = strModified ;
  5. Done. Lets see if it works.
  6. Run the code to verify results.

No comments:

Post a Comment