Can't see a new subview

杀马特。学长 韩版系。学妹 提交于 2019-12-12 02:18:24

问题


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?

(done in response to a button click)

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];

回答1:


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.windowthe warning went away and your provided code works as expected.

Updated code

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];

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];
}

An instance of NSViewController ain't got a property of window - only NSWindowController has one.



来源:https://stackoverflow.com/questions/26203988/cant-see-a-new-subview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!