Search code examples
iosuitableviewuitextfielduitextfielddelegate

Displaying placeholder text in UITextField created through data source


Background: I have a UITableView which has three rows with custom UITextFields that are populated from a TableDataSource. The default text in these text fields is also populated from the data source (default values for database fields).

I am able to automatically clear the UITextField when a user selects / clicks on a particular UITextField.

Problem: If a user selects a particular UITextField but then moves onto another UITextField without editing the text then I would like the original default text to re-appear. I have tried setting the UITextField to nil in the delegate's 'didEndEditing' method and that did not work.

Can someone please advise if they know of a way to accomplish this?


Solution

  • You can simple do it using the placeholder property of UITextField, but the text will appear as a little blurred manner, if you want to show the previous value then you can use the following solution:

    You can do it using the textFieldDidEndEditing delegate method.

     - (void)textFieldDidEndEditing:(UITextField *)textField
    {
       if(textField.text.lenght == 0)
       {
          textField.text = yourPreviousText;
       }
    }
    

    And in textFieldShouldBeginEditing

    - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
    {
       yourPreviousText = textField.text;
    }
    

    yourPreviousText is a NSString object declared in the class scope.