Sunday, June 2, 2013

UITextField placeholder example in Objective C (iOS).


UITextField placeholder

The string that is displayed when there is no other text in the text field.

@property(nonatomic, copy) NSString *placeholder

Discussion of [UITextField placeholder]
This value is nil by default. The placeholder string is drawn using a 70% grey color.

UITextField placeholder example.
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    textField.placeholder = nil;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    textField.placeholder = @"Your Placeholdertext";
}

Example of [UITextField placeholder].
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    textField.placeholder = nil;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
   if ([textField.text isEqualToString:@""] || [[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0))
   {
       [textField setText:@""];
       textField.placeholder = @"Your Placeholdertext";
   }
}

UITextField placeholder example.
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@"placeholder text here..."]) {
         textView.text = @"";
         textView.textColor = [UIColor blackColor]; //optional
    }
    [textView becomeFirstResponder];
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@""]) {
        textView.text = @"placeholder text here...";
        textView.textColor = [UIColor lightTextColor]; //optional
    }
    [textView resignFirstResponder];
}

End of UITextField placeholder example article.