views:

168

answers:

2

How would I add the text from the title of the button in my NSButton subclass?

+2  A: 

Here's how I think it might work:

- (void) drawRect:(NSRect)aRect {

    // other drawing commands
    // ...
    // other drawing commands

    NSDictionary *att = nil;

    NSMutableParagraphStyle *style =
      [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    [style setLineBreakMode:NSLineBreakByWordWrapping];
    [style setAlignment:NSCenterTextAlignment];
    att = [[NSDictionary alloc] initWithObjectsAndKeys:
                        style, NSParagraphStyleAttributeName, 
                        [NSColor whiteColor],
                        NSForegroundColorAttributeName, nil];
    [style release];

    [self.title drawInRect:self.bounds withAttributes:att];
    [att release];
}

based on a bit of Objective-C knowledge on an iPhone and looking at

http://www.cocoadev.com/index.pl?DrawingABoundedString

You may or may not be comfortable with the web site example's use of a static variable.

As you can probably gather I'm not. I get the impression the current graphics context is implicit in the call.

You probably want to vary the text position/color depending on button state.

EDIT

Code edited to fix memory leak.

martinr
+2  A: 

You subclass NSButtonCell, and override one or more of the various draw methods available to NSButtonCell and NSCell.

Darren