无法看到新的子视图 [英] Can't see a new subview
问题描述
所有我想做的是在我的NSWindow实例的内容视图中添加一个新的视图。当我做以下我没有看到新的视图(应该是黑色的,占据整个窗口)。我做错了什么?
All I am trying to do is add a new view to the content view of my NSWindow instance. When I do the following I do not see the new view (which should be black and take up the entire window). What am I doing wrong?
(响应按钮点击完成)
NSRect frameRect = [self.window frame];
frameRect.origin = NSZeroPoint;
NSView *view = [[NSView alloc] initWithFrame:frameRect];
view.wantsLayer = YES;
view.layer.backgroundColor = [NSColor blackColor].CGColor;
[self.window.contentView addSubview:view];
推荐答案
我已经设置了一个简单的项目按钮,并获得访问 self.window
的警告。当使用 self.view.window
时,警告消失,您提供的代码正常工作。
I've set up a simple project with a push button inside a ViewController and got a warning for accessing self.window
. When using self.view.window
the warning went away and your provided code works as expected.
更新代码
NSRect frameRect = [self.view.window frame];
frameRect.origin = NSZeroPoint;
NSView *view = [[NSView alloc] initWithFrame:frameRect];
view.wantsLayer = YES;
view.layer.backgroundColor = [NSColor blackColor].CGColor;
[self.view.window.contentView addSubview:view];
更新
使用WindowController的一个实例,你可以通过编程方式添加一个按钮。你的代码可以正常工作。
Update
Assuming that you're using an instance of WindowController where you're adding a button programmatically, your code works as expected.
@implementation WindowController
- (void)windowDidLoad
{
[super windowDidLoad];
CGRect buttonRect = CGRectMake(self.window.frame.size.width / 2 - 50,
self.window.frame.size.height / 2,
100,
50);
NSButton *button = [[NSButton alloc] initWithFrame:NSRectFromCGRect(buttonRect)];
[button setTitle: @"Click me!"];
[button setTarget:self];
[button setAction:@selector(buttonPressed)];
[self.window.contentView addSubview:button];
}
- (void)buttonPressed
{
NSRect frameRect = [self.window frame];
frameRect.origin = NSZeroPoint;
NSView *view = [[NSView alloc] initWithFrame:frameRect];
view.wantsLayer = YES;
view.layer.backgroundColor = [NSColor blackColor].CGColor;
[self.window.contentView addSubview:view];
}
NSViewController的实例
没有属性 window
- 只有 NSWindowController
有一个。
An instance of NSViewController
ain't got a property of window
- only NSWindowController
has one.
这篇关于无法看到新的子视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!