UITextView实现placehold功能

I found myself a verry easy way to imitate a place-holder

  1. in the NIB or code set your textView's textColor to lightGrayColor (most of the time)
  2. make sure that your textView's delegate is linked to file's owner and implement UITextViewDelegate in your header file
  3. set the default text of your textview to (example: "Foobar placeholder")
  4. implement: (BOOL) textViewShouldBeginEditing:(UITextView *)textView

Edit:

Changed if statements to compare tags rather than text. If the user deleted their text it was possible to also accidentally delete a portion of the place holder @"Foobar placeholder".This meant if the user re-entered the textView the following delegate method, -(BOOL) textViewShouldBeginEditing:(UITextView *) textView, it would not work as expected. I tried comparing by colour of text in the if statement but found that light grey color set in interface builder is not the same as light grey colour set in code with [UIColor lightGreyColor]

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

It is also possible to reset the placeholder text when the keyboard returns and the [textView length] == 0

EDIT:

Just to make the last part clearer - here's is how you can set the placeholder text back:

-(void)textViewDidChange:(UITextView*)textView
{if([textView.text length]==0){
       textView.text =@"Foobar placeholder";
       textView.textColor =[UIColor lightGrayColor];
       textView.tag =0;}}

posted on 2012-11-05 19:06  kiao295338444  阅读(351)  评论(0编辑  收藏  举报

导航