macoscocoanstextview

Set the placeholder string for NSTextView


Is there any way to set the placeholder string for NSTextView like that in NSTextField? I have checked the property but couldn't find it. I have searched some questions but there isn't a proper explanation.


Solution

  • I found this answer online. Philippe Mougin made this.

    static NSAttributedString *placeHolderString;
    
    @implementation TextViewWithPlaceHolder
    
    +(void)initialize
    {
      static BOOL initialized = NO;
      if (!initialized)
    {
         NSColor *txtColor = [NSColor grayColor];
         NSDictionary *txtDict = [NSDictionary dictionaryWithObjectsAndKeys:txtColor, NSForegroundColorAttributeName, nil];
         placeHolderString = [[NSAttributedString alloc] initWithString:@"This is my placeholder text" attributes:txtDict];
     }
    }
    
    - (BOOL)becomeFirstResponder
    {
      [self setNeedsDisplay:YES];
      return [super becomeFirstResponder];
    }
    
    - (void)drawRect:(NSRect)rect
    {
      [super drawRect:rect];
     if ([[self string] isEqualToString:@""] && self != [[self window] firstResponder])
     [placeHolderString drawAtPoint:NSMakePoint(0,0)];
    }
    
    - (BOOL)resignFirstResponder
    {
       [self setNeedsDisplay:YES];
       return [super resignFirstResponder];
    }
    
    @end