Placeholder in UITextView

前端 未结 30 3124
野趣味
野趣味 2020-11-22 16:01

My application uses an UITextView. Now I want the UITextView to have a placeholder similar to the one you can set for an UITextField.<

30条回答
  •  旧巷少年郎
    2020-11-22 16:07

    I found myself a very 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 text view 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 the color of the text in the if statement but found that light grey color set in interface builder is not the same as light grey color 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;
       }
    }
    

提交回复
热议问题