Question

I am trying to achieve something which may or may not be possible, but if it is, I have not found a way.

I have a UITextView that is populated with the words "Additional Notes: " in the form of a placeholder (because you can't directly have placeholder texts with a UITextView).

When I tap on the UITextView, it creates a new line character and the user can start typing.

What I want to achieve is for the "Additional Notes: " text to be in Gray, but the typed in text to appear in white.

Is this possible?

In my view, I have:

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {

    if([[textView text] isEqualToString:@"Additional Notes: "]){
        [textView setText:@"Additional Notes: \n"];
    }
    return YES;

}

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

    if([[[textView text] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""]){
        [textView setText:@"Additional Notes: "];
    }
    return YES;
}

In the viewDidLoad, I set the text to Grey:

self.notesTextView.textColor = [UIColor grayColor]; 

In the shouldChangeTextInRage, I tried putting the colour white in there with an if condition, but what happens is, the "Additional Notes: " changes to white as well as soon as I start typing.

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    self.notesTextView.textColor = [UIColor whiteColor];
    if ([text isEqualToString:@"\n"])
    {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

Is what I'm trying to achieve, possible? If so, how would I go about doing it?

Was it helpful?

Solution

You need to find the range of the @"Additional Notes: " substring using the

NSRange *rangeOfPlaceholder =[[textView text] rangeOfString:@"Additional Notes: "];

and then create attributedtext and set it to the textView as follows in your textview delegates while editing:-

NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:textView.text];
[attString addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:rangeOfPlaceholder];
[attString addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:rangeOfRemainingEnteredText];

[textView setAttributedText:attString];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top