Wednesday, January 29, 2014

Placeholder in UITextView

UITextField has a placeholder property but one doesn't exist in UITextView. However, it is possible to overcome this limitation with usage of the UIViewDelegate.
#import 
@interface MyViewController : UIViewController <UITextViewDelegate>
@end
Declare a UITextView property in the class continuation category. Set up the text view, the delegate and add the placeholder text default text for the placeholder.
static NSString *const kPlaceholderText = @"Placeholder";

@interface MyViewController ()
@property (nonatomic, retain) UITextView *myTextView;
@end

UITextView *textViewTemp = [[UITextView alloc] initWithFrame:CGRectMake(10, 80, 300, 115)];
self.myTextView = textViewTemp;
[self.myTextView setDelegate:self];
[self.myTextView setText:kPlaceholderText];
[self.myTextView setTextColor:[UIColor colorWithRed:200/256.0 green:200/256.0 blue:200/256.0 alpha:1.0]];
Now implement the UITextView delegate methods.
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    if ([self.myTextView.textColor isEqual:[UIColor colorWithRed:200/256.0 green:200/256.0 blue:200/256.0 alpha:1.0]] ){
        self.myTextView.text = @"";
        self.myTextView.textColor = [UIColor blackColor];
    }
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    if(self.myTextView.text.length == 0){
        self.myTextView.textColor = [UIColor colorWithRed:200/256.0 green:200/256.0 blue:200/256.0 alpha:1.0];
        self.myTextView.text = kPlaceholderText;
        [self.myTextView resignFirstResponder];
    }
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    if(self.myTextView.text.length == 0){
        self.myTextView.textColor = [UIColor colorWithRed:200/256.0 green:200/256.0 blue:200/256.0 alpha:1.0];
        self.myTextView.text = kPlaceholderText;
        [self.myTextView resignFirstResponder];
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if([text isEqualToString:@"\n"]) {
        [myTextView resignFirstResponder];
        return NO;
    }
    return YES;
}
textViewShouldBeginEditing looks to see if the existing text is the color of the placeholder text and if so clears out the placeholder text and sets the correct color for the regular text. textViewShouldEndEditing and textViewDidChange checks to see if the text view is empty and sets the placeholder text and color. Finally, shouldChangeTextInRange checks if the user selects return. Implementing the UITextView delegate methods mimics the placeholder behavior of UITextField.

No comments:

Post a Comment