Search code examples
objective-cmacoscocoanstextfieldnstextfieldcell

Drawing fixed symbol inside NSTextField


I have a NSTextField and I would like a symbol to always appear at the far left, with the content of the text field beginning to the right of it. For example you can imagine a text field with a dollar sign ($) prefixed at the far left. One could just add a label on top of it then subclass NSTextFieldCell to add left padding, which I've done, but I need to reuse this text field in various locations so I would prefer to draw the symbol directly in the NSTextFieldCell subclass if possible. I noticed the drawWithFrame:inView: method, is that where this drawing code should be placed? If so, how does one properly draw a label in that frame?


Solution

  • You can do the drawing inside drawWithFrame:inView: . After your drawing modify the rect before calling the "[super drawWithFrame]. like

    -(void)drawWithFrame:(NSRect)rect inView:(NSView*)view
    {
      NSString *str = @"$";
      NSRect someRect;//string draw rect
      [str drawInRect:someRect withAttributes:nil];
      rect.origin.x += someRect.size.width;
      rect.size.width -= someRect.size.width;
      [super drawWithFrame:rect inView:view];
    
    }