2009-07-27 97 views

回答

7

使用覆盖drawingRectForBounds:的自定义NSTextFieldCell。让它尽可能多地嵌入矩形,然后将新矩形传递给[super drawingRectForBounds:]以获得正常的填充,并返回该调用的结果。

+0

我明白了,我会在方法中定义多少内容,或者是否存在一些示例代码? – Joshua 2009-07-27 16:47:30

+0

如果您不熟悉NSRect,请尝试http://www.cocoadev.com/index.pl?NSRect。 – smorgan 2009-07-27 18:02:16

9

smorgan的回答指向了正确的方向,但我花了相当长的一段时间才弄清楚如何恢复自定义文本框显示背景色的能力 - 您必须在自定义单元上调用setBorder:YES

这是为时已晚,以帮助约书亚,但这里的你如何实现自定义单元格:

#import <Foundation/Foundation.h> 
// subclass NSTextFieldCell 
@interface InstructionsTextFieldCell : NSTextFieldCell {   
} 
@end 

#import "InstructionsTextFieldCell.h" 

@implementation InstructionsTextFieldCell 

- (id)init 
{ 
    self = [super init]; 
    if (self) { 
     // Initialization code here. (None needed.) 
    } 
    return self; 
} 

- (void)dealloc 
{ 
    [super dealloc]; 
} 

- (NSRect)drawingRectForBounds:(NSRect)rect { 

    // This gives pretty generous margins, suitable for a large font size. 
    // If you're using the default font size, it would probably be better to cut the inset values in half. 
    // You could also propertize a CGFloat from which to derive the inset values, and set it per the font size used at any given time. 
    NSRect rectInset = NSMakeRect(rect.origin.x + 10.0f, rect.origin.y + 10.0f, rect.size.width - 20.0f, rect.size.height - 20.0f); 
    return [super drawingRectForBounds:rectInset]; 

} 

// Required methods 
- (id)initWithCoder:(NSCoder *)decoder { 
    return [super initWithCoder:decoder]; 
} 
- (id)initImageCell:(NSImage *)image { 
    return [super initImageCell:image]; 
} 
- (id)initTextCell:(NSString *)string { 
    return [super initTextCell:string]; 
} 
@end 

(如果像约书亚,你只需要在左边的插图,离开origin.y和高度是,与相同的量添加到该宽度 - 不双 - 你做到origin.x)

分配这样的定制单元,在窗口/视图控制器的awakeFromNib方法,其拥有文本框:

// Assign the textfield a customized cell, inset so that text doesn't run all the way to the edge. 
InstructionsTextFieldCell *newCell = [[InstructionsTextFieldCell alloc] init]; 
[newCell setBordered:YES]; // so background color shows up 
[newCell setBezeled:YES]; 
[self.tfSyncInstructions setCell:newCell]; 
[newCell release];