How to insert placeholder in UITextView?

Nikunj Jadav picture Nikunj Jadav · Aug 12, 2011 · Viewed 96.8k times · Source

Is there any way to insert a placeholder in a UITextView similar to the UITextField? If yes, then please send me any link or any idea to implement this functionality.

Answer

PJR picture PJR · Aug 12, 2011

It is not possible to create placeholder in UITextView but you can generate effect like place holder by this.

- (void)viewDidLoad {   
    commentTxtView.text = @"Comment";
    commentTxtView.textColor = [UIColor lightGrayColor];
    commentTxtView.delegate = self;

}
- (BOOL) textViewShouldBeginEditing:(UITextView *)textView {
    commentTxtView.text = @"";
    commentTxtView.textColor = [UIColor blackColor];
    return YES;
}

-(void) textViewDidChange:(UITextView *)textView {

    if(commentTxtView.text.length == 0) {
        commentTxtView.textColor = [UIColor lightGrayColor];
        commentTxtView.text = @"Comment";
        [commentTxtView resignFirstResponder];
    }
}

-(void) textViewShouldEndEditing:(UITextView *)textView {

    if(commentTxtView.text.length == 0) {
        commentTxtView.textColor = [UIColor lightGrayColor];
        commentTxtView.text = @"Comment";
        [commentTxtView resignFirstResponder];
    }
}

OR you can add label in textview just like

lbl = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 0.0,textView.frame.size.width - 10.0, 34.0)];

[lbl setText:kDescriptionPlaceholder];
[lbl setBackgroundColor:[UIColor clearColor]];
[lbl setTextColor:[UIColor lightGrayColor]];
textView.delegate = self;

[textView addSubview:lbl];

and set

- (void)textViewDidEndEditing:(UITextView *) textView {
    if (![textView hasText]) {
        lbl.hidden = NO;
    }
}

- (void) textViewDidChange:(UITextView *)textView {
    if(![textView hasText]) {
        lbl.hidden = NO;
    }
    else {
        lbl.hidden = YES;
    }  
}