2

如何在我的 NSButton 子类中添加按钮标题中的文本?

4

2 回答 2

4

以下是我认为它可能起作用的方式:

- (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];
}

基于一些关于 iPhone 的 Objective-C 知识并查看

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

您可能对网站示例使用静态变量感到满意,也可能不满意。

正如你可能猜到的那样,我不是。我得到的印象是当前的图形上下文隐含在调用中。

您可能希望根据按钮状态改变文本位置/颜色。

编辑

编辑代码以修复内存泄漏。

于 2009-12-18T21:21:13.437 回答
3

您可以继承NSButtonCell和覆盖 和可用的各种draw方法中的一种或多种。NSButtonCellNSCell

于 2009-12-18T21:31:03.833 回答