I'm currently experiencing a problem like the one described in this SO question (which does not currently have an accepted answer), in that my text fields' placeholder text is not visible unless the text field is selected.
I have subclassed NSTextField
(code below):
@interface CustomTextField : NSTextField
@property (nonatomic, strong) IBInspectable NSImage *backgroundImage;
@end
@implementation CustomTextField
- (void)awakeFromNib
{
[self setDrawsBackground:NO];
}
- (void)drawRect:(NSRect)rect
{
NSImage *backgroundImage = self.backgroundImage;
[super drawRect:rect];
[self lockFocus];
[backgroundImage drawInRect:rect fromRect:rect operation:NSCompositeSourceOver fraction:1.0];
[self unlockFocus];
}
@end
I've set the class of my text field in Interface Builder to be CustomTextField
, and set the placeholder text as shown below:
As can be seen in the screenshots below, the placeholder text is only visible if the text field is selected...
Text field one:
Text field two:
Does anyone have any idea on how I can make the placeholder text visible regardless of if the user has selected it? Thank you!
You are drawing your background image after the superclass has drawn its content. So, you are probably drawing over whatever the superclass has drawn, replacing it.
You should presumably draw your background image first, before calling through to super. Also, you shouldn't lock focus (or unlock it) in -drawRect:
. The frameworks have already done that for you.
The reason why the placeholder shows up when your text field has focus is that you're actually seeing the field editor, not the text field at that point. The field editor is an instance of NSTextView
("view", not "field") that's inserted into the view hierarchy on top of the text field to handle text editing duties. So, when the text field has focus, your custom class's drawing it irrelevant.