NSTextField - Subclassing & drawRect causes text to not load

Trying to round the border of NSTextField (small black box in the upper left corner): http://cl.ly/image/2V2L1u3b3u0G

So, I have subclassed NSTextField:

MYTextField.h

#import <Cocoa/Cocoa.h> @interface HATrackCounterField : NSTextField @end 

MYTextField.m

 #import "HATrackCounterField.h" @implementation HATrackCounterField - (id)initWithFrame:(NSRect)frame { self = [super initWithFrame:frame]; if (self) {} return self; } - (void)drawRect:(NSRect)dirtyRect { [[NSColor blackColor] setFill]; [[NSBezierPath bezierPathWithRoundedRect:dirtyRect xRadius:3.0 yRadius:3.0] fill]; } @end 

Now it does not show the text of the text field: http://cl.ly/image/1J2W3K431C04

I'm new to objective-c, it seems like this should be easy, so I'm probably just doing something wrong ...

Thanks!

Note. I set the text as a collection, and I tried setStringValue: at different points also to no avail.

+4
source share
2 answers

The text of the text field is not displayed because you overwrite -drawRect and do not call [super drawRect:dirtyRect] in it.

In your case, I think that the easiest way to do what you want is to use a clip mask: just NSTextField do an ant drawing, then pin the area:

 - (void)drawRect:(NSRect)dirtyRect { [NSGraphicsContext saveGraphicsState]; [[NSBezierPath bezierPathWithRoundedRect:dirtyRect xRadius:3.0 yRadius:3.0] setClip]; [super drawRect:dirtyRect]; [NSGraphicsContext restoreGraphicsState]; } 

In general, it is better to subclass NSTextFieldCell instead to make a custom drawing, because the cells are responsible for drawing.

+5
source

For reference to future readers, this is probably the way you should do this, by subclassing NSTextFieldCell :

 - (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView { NSBezierPath *betterBounds = [NSBezierPath bezierPathWithRoundedRect:cellFrame xRadius:CORNER_RADIUS yRadius:CORNER_RADIUS]; [betterBounds addClip]; [super drawWithFrame:cellFrame inView:controlView]; if (self.isBezeled) { // optional, but provides an example of drawing a prettier border [betterBounds setLineWidth:2]; [[NSColor colorWithCalibratedRed:0.510 green:0.643 blue:0.804 alpha:1] setStroke]; [betterBounds stroke]; } } 

I draw an extra blue border here (although this seems unnecessary for your black box)

+3
source

All Articles