【发布时间】:2013-06-06 10:24:53
【问题描述】:
我有一个带背景的文本字段,但要使其看起来正确,文本字段的左侧需要有一些填充,有点像 NSSearchField 所做的那样。如何在 left 上为文本字段添加一些填充?
【问题讨论】:
标签: objective-c cocoa
我有一个带背景的文本字段,但要使其看起来正确,文本字段的左侧需要有一些填充,有点像 NSSearchField 所做的那样。如何在 left 上为文本字段添加一些填充?
【问题讨论】:
标签: objective-c cocoa
smorgan 的回答为我们指明了正确的方向,但我花了很长时间才弄清楚如何恢复自定义文本字段显示背景颜色的能力——您必须在自定义单元格上调用 setBorder:YES。
现在帮助 Joshua 为时已晚,但以下是您实现自定义单元格的方法:
#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
(如果像 Joshua 一样,您只想在左侧插入一个插图,请保留 origin.y 和 height 不变,并在宽度上添加相同的量 - 而不是加倍 - 就像对 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];
【讨论】:
使用覆盖drawingRectForBounds: 的自定义NSTextFieldCell。让它插入你想要的矩形,然后将新矩形传递给 [super drawingRectForBounds:] 以获得正常的填充,并返回该调用的结果。
【讨论】: