我有一个带背景的文本字段,但为了使它看起来正确,文本字段需要在它的左侧有一些填充,有点像NSSearchField。如何在左侧上为文本字段添加一些填充?
答案 0 :(得分:9)
smorgan的回答指出了我们正确的方向,但是我花了很长时间才弄清楚如何恢复自定义文本字段显示背景颜色的能力 - 你必须在自定义单元格上调用setBorder:YES
。 / p>
这对帮助约书亚来说已经太晚了,但这是你如何实现自定义单元格的:
#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和高度,并将相同的数量加到宽度上 - 而不是加倍 - 就像你对原始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];
答案 1 :(得分:7)
使用覆盖drawingRectForBounds:的自定义NSTextFieldCell。让它按照你想要的方式插入矩形,然后将新矩形传递给[super drawingRectForBounds:]以获得正常的填充,并返回该调用的结果。