将填充添加到文本字段的"左侧"

Jos*_*hua 3 cocoa objective-c

我有一个带背景的文本字段,但为了使它看起来正确,文本字段需要在它的左侧有一些填充,有点像NSSearchField.我如何给左边的文本字段添加一些填充?

Wie*_*nke 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
Run Code Online (Sandbox Code Playgroud)

(如果像Joshua一样,你只需要左边的插图,保留origin.y和height,并将相同的数量加到宽度上 - 而不是加倍 - 就像你对origin.x一样.)

在拥有textfield的窗口/视图控制器的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];
Run Code Online (Sandbox Code Playgroud)


smo*_*gan 7

使用覆盖drawingRectForBounds的自定义NSTextFieldCell : . 让它按照你想要的方式插入矩形,然后将新矩形传递给[super drawingRectForBounds:]以获得正常的填充,并返回该调用的结果.