我正在尝试以编程方式创建一个带有自定义 contentView
和一个自定义 NSTextField
控件的窗口,但我在绘制窗口和 View 的层次结构时遇到问题他们自己。
我创建一个自定义无边框窗口并覆盖它的 setContentView
/contentView
访问器。这似乎工作正常,并且调用自定义 contentView 的 initWithFrame 和 drawRect 方法,导致 contentView 正确绘制自身。
但是,一旦我尝试以编程方式将自定义 NSTextField
添加到 contentView
中,它就不会被添加或绘制。通过说自定义,我的意思是我覆盖它指定的初始值设定项(initWithFrame:frame
- 仅用于自定义字体设置)和drawRect方法,如下所示:
- (void)drawRect:(NSRect)rect {
NSRect bounds = [self bounds];
[super drawRect:bounds];
}
自定义 contentView 的初始化程序如下所示:
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self != nil) {
// i want to draw itself to the same
// size as contentView thus i'm using same frame
CustomTextField *textField = [[CustomTextField alloc] initWithFrame:frame];
[self addSubview:textField];
[self setNeedsDisplay:YES];
}
return self;
}
我已经为此苦苦挣扎了几个小时,所以非常感谢您的指点。可根据要求提供更多代码。)
最佳答案
你的 -drawRect: override 对我来说似乎是错误的,为什么你会故意忽略传入的 rect 参数?为什么这是必要的?
至于为什么文本字段没有出现,很可能是因为你没有配置它。当您在代码中创建 NSTextField 时,您不会获得与将文本字段拖到 IB 中的 View 上时获得的默认实例相同的结果。您需要配置 NSTextField 及其 NSTextFieldCell 以获得您想要的外观。
我正在使用以编程方式添加的文本字段,其配置如下:
_textField = [[NSTextField alloc] initWithFrame:textFieldRect];
[[_textField cell] setControlSize:NSSmallControlSize];
[_textField setFont:[NSFont systemFontOfSize:[NSFont smallSystemFontSize]]];
[_textField setBezelStyle:NSTextFieldSquareBezel];
[_textField setDrawsBackground:YES];
[_textField setBordered:YES];
[_textField setImportsGraphics:NO];
[_textField setAllowsEditingTextAttributes:NO];
[_textField setBezeled:YES];
[_textField sizeToFit];
[self addSubview:_textField];
[_textField setFrame:textFieldRect];
[_textField setAutoresizingMask:NSViewMinXMargin];
关于objective-c - 在添加的 subview 上未调用drawRect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1481046/