Wednesday, 12 February 2014

Placeholder text in UITextView iOS

As we all know UITextView does not have a Placeholder unlike a UITextField.
So it is really a painful job to have a placeholder text in a UITextView.
I got stuck on the same issue and did some work around.
This trick will make you think that you are actually having a placeholder text inside a UITextView.

So here we go:
1. Place a UILabel on nib (xib) file at the position where you want UITextView.
2. Now set text what you want on the placeholder and change it text color to lightGraycolor.
3. Take a UITextView and place it above the UILabel and set its background color to clearcolor.
4. It will appear as a placeholder inside UITextView.
5. Set delegates of UITextView as follows:

In Header file:
#import <UIKit/UIKit.h>

@interface LoginViewController : UIViewController <UITextViewDelegate>


In Implementation file:

- (void)viewDidLoad {

    [super viewDidLoad];
    [myTextView setDelegate:self];

6. Take textViewDidChange delegate method of UITextView.
6. Here set UILabel to hidden YES and set background color of UITextView to white when UITextView does not have text.
7. And in else condition set UILabel to hidden NO and set background color of UITextView to clearcolor when UITextView.

- (void)textViewDidChange:(UITextView *)textView {
    // Enable and disable lblPlaceHolderText
    if ([textView.text length] > 0) {
        [textView setBackgroundColor:[UIColor whiteColor]];
        [lblPlaceHolderText setHidden:YES];
    } else {
        [textView setBackgroundColor:[UIColor clearColor]];
        [lblPlaceHolderText setHidden:NO];

Sample code: HERE

Image: Before typing the placeholder is visible.

Image: After typing placeholder hides.